[Vuejs]-How to pass parameter to a Vue component to initiate components instance

2👍

Here is the working fiddle: 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>'
})

I think you need to maintain state inside the button-counter component. Also rename 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>

1👍

See your updated fiddle. You are directly mutating the count property, save it as a data first and mutate the internalCount. Also, use a : to cast the prop to a Number and not a string.

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

1👍

You can not change props in child component.
You should use $emit to change props:

parent component:

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

and 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>

Leave a comment