Steps for initializing a Vue component instance by passing parameters

Being a novice in the realm of Vue, I am eager to gain knowledge on how to effectively create and reuse Vue components. However, I am encountering an issue where the initial data passed to a component does not update upon a click event. Shown below is a snippet of my code (full version available at https://jsfiddle.net/gpawel/486ysvxj/33/). Could you please point out what might be causing this problem? Thank you.

<div id="components-demo">
  <button-counter count='3'></button-counter>
  <br><br>
  <button-counter count='4'></button-counter>
</div>

Vue.component('button-counter', {
    props: ['count'],
    methods: {
    add: function() {
        return {count: count++}
    }
  },
  template: '<button v-on:click="add()">You clicked me {{count}}  times.</button>'
})

new Vue({ 
    el: '#components-demo'
})

Answer №1

Check out the live demo here: https://jsfiddle.net/68p1u9ks/

Vue.component('button-counter', {
    props: ['initialCount'],
    data: function () {
        return {
          count: 0,
        }
    },
    methods: {
        add: function() {
            this.count++
        },
    },
    created() {
          this.count = this.initialCount
    },
    template: '<button v-on:click="add()">You clicked me {{count}} times.</button>'
})

In my opinion, it is important to keep track of the state within the button-counter component. Additionally, consider renaming the count prop to initial-count.

<div id="components-demo">
  <button-counter :initial-count='3'></button-counter>
  <br><br>
  <button-counter :initial-count='4'></button-counter>
</div>

Answer №2

Check out the updated JSFiddle for your reference. Avoid directly changing the count property, instead store it as a data first and then update the internalCount. Also, make sure to use a colon (:) when casting the prop to a Number rather than a string.

props: ['count'],
  data() {
  return {
    internalCount: this.count
  }
},
methods: {
  add: function() {
    return {
      count: this.internalCount++
    }
  }
},

Answer №3

Updating props in a child component is not possible directly. To modify props, you can utilize the $emit method:

Example of parent component:

<template>
<div>
  <child :count="count" @add="add" />
</div>
</template>
<script>
export default {
  data() {
    return {
      count: 1
    };
  },
  methods: {
   add() {
     this.count += 1;
   }  
  }
}
</script>

Example of child component:

<template>
  <button v-on:click="add()">You clicked me {{inComponentCount}} times.</button>
</template>
<script>
export default {
  props: [count],
  computed: {
    inComponentCount() {
      return this.count;
    }
  },
  methods: {
   add() {
     this.$emit('add')
   }  
  }
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

(basic) Issue with Jquery ajax request not receiving data

The alert box is not displaying anything and is not returning any data from the specified URL, even though it should show the Google page! Any suggestions? I am using the POST method because I need to send querystring data as well. $.ajax({ ...

The method window.scrollTo() may encounter issues when used with overflow and a height set to 100vh

Suppose I have an HTML structure like this and I need to create a button for scrolling using scrollTo. However, I've come across the information that scrollTo doesn't work well with height: 100vh and overflow: auto. What would be the best way to ...

Using an AWS API Gateway, an HTTP client sends a request to access resources

I have a frontend application built with Angular and TypeScript where I need to make an HTTP request to an AWS API Gateway. The challenge is converting the existing JavaScript code into TypeScript and successfully sending the HTTP request. The AWS API gat ...

Tips for retrieving a selected date from an HTML textbox labeled as "Date"

My goal was to find the differences between two dates by utilizing an HTML Date textbox. <input type="text" name="datein" id="datein" value="" class="inputtexbox datepicker" style="display: none" is-Date/> <input type="text" name="dateto" id=" ...

Tips for achieving a background animation similar to the one shown on this page

Check out this link: danielcoding.me/resume/#contact I am interested in this animation: screenshot I tried inspecting element on the page, but couldn't find any background images. How can I create this animation? Is it achieved through JavaScript or ...

What is the reason behind not requiring to invoke the next function in a Sails.js controller method, even when it includes an asynchronous database query?

Sample controller function: fetchArticles: function(req, res) { Articles.find({}).exec(function(err, articles) { res.json(articles) // It appears this part is asynchronous // Is next() required here? }) } In my experience, I typicall ...

Solution: The issue where the children's onChange event was not updating the parent in Ant Design was discovered to be due to the Select and Table components nested inside a Tab not changing according to the pageSize

I'm facing an issue with updating a parent element when the children's onChange event is triggered. Specifically, I have an Ant Design Select and Table inside a Tab that are not reflecting changes in the pageSize value. Although setPageSize func ...

Using Vue.js to Authenticate Users with JWT Tokens Sent in Registration Emails

Hey everyone, I could really use some assistance with JWT tokens. I created a registration form using Vue.js and sent the data to the database using axios. Now, I need help figuring out how to save the token I receive in the confirmation email so that I ca ...

Include a <div> element to display the date in an HTML format, ensuring that the days and months

I am working on a project where I have a list of dates and I need to format them by adding div tags to separate the days, months, and years into different divisions. <div class="campaign">30/11/2016 - <a href="#" target="_blank">Dummy Text& ...

Is it truly necessary to remove packages from devDependencies to improve performance?

It is a common understanding that packages listed under devDependencies are typically not included in the final build. So why do we remove them for the sake of performance optimization? For instance, there are discussions about replacing Moment.js with a ...

Utilizing Google+ Snippet and Open Graph Protocol for Enhanced Visibility

I am currently facing an issue with my dynamically built web page where the links shared on Google+ are not showing snippets properly. I have followed the example snippet for article rendering and documentation provided here: https://developers.google.com ...

HTML comment without the presence of javascript

Is it possible to use different expressions besides checking for the browser or version of IE in order to display/hide content? For example: <!--[if 1 == 0]--> This should be hidden <!--[endif]--> I am considering this option because I send o ...

Implementing automatic dark mode activation during nighttime with jQuery or JavaScript

I'm looking to implement an automatic dark mode feature on my website that switches on at night and off during the day or morning. Currently, my website has a dark mode toggle code that allows users to switch between dark and light modes using local ...

Access the data within a jsonArray using Cypress

I'm dealing with a test.json file that contains a jsonArray [{ "EMAIL": "email_1", "FIRST_NAME": "Daniel" }, [{ "EMAIL": "email_2", "FIRST_NAME": "John" }] ] I'm trying to figure out how to use cypre ...

MUI - Material-table/core - Checkbox selection malfunctioning on click event

UPDATE : The matter also pertains to Material Ui's Data table. I attempted to replicate the issue using the provided example in the documentation but encountered the same problem. I have been struggling with an issue related to the selection feature ...

Creating an effective Google Login Button in a React application

Struggling to implement a Login/Sign In Google Button on my page using react, I'm new to this framework and it's just not working as expected. Following tutorials from the internet but still facing issues. To summarize, I'm utilizing tailw ...

Is it possible to display this code through printing rather than using an onclick event?

I have a puzzle website in the works where users select a puzzle to solve. I am looking for a way to display the puzzles directly on the website instead of using pop-up boxes. I am proficient in various coding languages, so any solution will work for me. ...

Adjust picture dimensions when the window changes (using jQuery)

Hey there, I'm in need of some help resizing images on my webpage. I want the images to adjust their size when the page loads or when the browser is resized. The images can be either portrait or landscape, and they will be contained within a div that ...

Tips for structuring route dependencies in Node.js and Express

Although I have a good grasp of exporting routes to an index.js file, my struggle lies in properly referencing external route dependencies without having to copy them to the top of the file. For instance, if I have the main entry point of the program (ind ...

Connecting to deeply nested attributes within an object using specified criteria

I apologize if the title of my query is not very descriptive, I couldn't come up with a better one. Please feel free to suggest improvements. I am currently working on developing a reusable "property grid" in Angular. My goal is to create a grid wher ...