[Vuejs]-What is a good vue.js design pattern for avoiding mutating props directly when you can't use computed properties

0👍

Here are some ways to handle this scenario, Vuex is a good option, but for three pages, I think is not necessary.

Using the .sync modifier

<Child :name.sync="childName"></Child>

And in the child component, you can update the value with an event

this.$emit('update:name', newName);

you can listen an event from child an update the parent data property

//parent component
<div>
  <input-name @updateName="eventToUpdateName" /> <!--child component-->
</div>
...
data: () => ({ nameFromChild: '' )},
methods: {
  eventToUpdateName(value) {
    this.nameFromChild = value; // Update from child value emitted
  }
}
...

And in the child component

// Child component
<input v-model="name" />
...
data: () => ({ name: '' }),
// watch for changes in the name property and emit an event, and pass the value to the parent
watch: { name() { this.$emit('updateName', this.name } }
...

Also, You can use a v-model directive and emit ‘input’ event from child.

//parent component
<div>
  <input-name v-model="nameFromChild" /> <!--child component-->
</div>
...
data: () => ({ nameFromChild: '' )}
...

Now in the child component you can have

// Child component
<div>
  <input v-model="name" />
</div>
data: () => ({ name: '' }),
props: { value: { type: String, default: '' },
created() { this.name = this.value }, // You can receive a default value
watch: { name() { this.$emit('input', this.name } }
...

Leave a comment