[Vuejs]-Vue deep cloning props in data is not responsive

0👍

There are two ways you could handle this: use the props directly and emit changes to the parent; or use computed properties to compute the value based on the data and props.

Emitting changes is probably what you want to do 99% of the time as any changes to the props either internal or external will change what your component is doing. Using computed props allows for changes to the props to be used only if the data hasn’t been modified internally.

Computed props

props: {
    defaultAccounts: Array,
    defaultSelected: Boolean,
    ...
}

data: () => ({
    customAccounts: null,
    customSelected: null,
})

computed: {
    accounts() {
        return (this.customAccounts == null) ? this.defaultAccounts : this.customAccounts
    },

    selected() {
        return (this.customSelected == null) ? this.defaultSelected : this.customSelected
    }
}

You could even define setters on the computed props to set the value of the data properties.

Emit changes

Component:

props: {
    accounts: Array,
    selected: Boolean,
    ...
}

methods: {
    accountsChanged(value) {
        this.$emit('update:accounts', value)
    },
    selectedChanged(value) {
        this.$emit('update:selected', value)
    }
}

Where you use component:

<my-component :accounts.sync="accounts" :selected.sync="false"></my-component>

See Sync Modifier Documentation for more info.

I haven’t tested this code so it may need tweaking to get it working correctly.

Leave a comment