[Vuejs]-Can I only sync v-model specifically with Vue.js?

1👍

First of all props are not supposed to be changed in a child component. So using v-model on props is kind of an anti pattern. What could be a solution for you is to assign the props on the mounted() method to data props, use v-model on those, and when the confirm button is pushed emit those data props to the parent.

<template>
    <v-form>
       <v-text-field v-model="name" label="name"/>
       <v-text-field v-model="password" label="password"/>
       <v-btn class="primary" @click="confirmed">Confirm</v-btn>
    </v-form>
</template>
<script>
export default {
    data() {
        return {
            name: '',
            password: ''
        }
    },
    props:{
        account:{
            type:Object,
            required:true,             
        }
    },
    mounted() {
        this.name = this.account.name;
        this.password = this.account.password;
    },
    methods: {
        confirmed() {
            this.$emit('confirmClicked', { name: this.name, password: this.password });
        }
    }
}
</script>


👤arm

0👍

What you are doing is a bad practice. You are modifing prop and that is what you should not be doing.

Best solution would be making a copy of an account object like this:

<template>
  <v-form>
     <v-text-field v-model="accountModel.name" label="name"/>
     <v-text-field v-model="accountModel.password" label="password"/>
     <v-btn class="primary" @click="updateAccount">Confirm</v-btn>
  </v-form>
</template>

<script>
export default {
  props: {
    account: {
      type: Object,
      required: true,             
    },
  },
  data() {
    return {
      accountModel: {
        ...this.account            
      },
    };
  },
  methods: {
    updateAccount() {
      this.$emit('update-account', this.accountModel);
    },
  },
}
</script>

And in your parent component simply listen for and update your prop data:

@update-account="account = $event"

Leave a comment