panthro
panthro

Reputation: 24061

Passing in props - should I set them to data?

If I pass in a prop called active:

<my-component :active="true" :count="10"></my-component>

On the component I have:

props: [
    'active',
    'count',
],

When working with these props inside the component should I set them as data attributes like so:

data() {
    return {
        dataActive: this.active,
    }
}, 

Or should I work directly with them as props?

Upvotes: 1

Views: 53

Answers (1)

thanksd
thanksd

Reputation: 55634

Vue will give you a warning if you attempt to modify the value of a prop:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value.

So, if your component is going to modify the value of this.active, then you should set the value to a data property. Otherwise, you don't need to.


A common example in which you would need to modify a prop's value is when implementing v-model on a component. In that case, your component would set the value property as a data property, and then emit an input event when the data property changed.

Here's a simple example of that:

Vue.component('child', {
  template: `
    <div>
      <button @click="bar++">up</button>
      <button @click="bar--">down</button>
    </div>
  `,
  props: { value: Number },
  data() {
    return { bar: this.value };
  },
  watch: {
    bar(val) {
      this.$emit('input', val);
    }
  }
});

new Vue({
  el: '#app',
  data() {
    return { foo: 1 };
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>

<div id="app">
  <child v-model="foo"></child>
  {{ foo }}
</div>

Upvotes: 1

Related Questions