简体   繁体   中英

Vue.js reactivity of data object property not triggered when using v-model

I have a component with data containing an object, this object has a property which is an array.

<template>
    <div>
        <product-selector :selected-products="order.selectedProducts" v-model="order.selectedProducts"/>
    </div>
</template>
data () {
    return {
        order: {
            selectedProducts: [],
        },
    };
}

Everytime a new product is selected/deselected in product-selector, I emit an "input" event with the new array. The problem is that the order object in the parent component is not reactive and is not triggering the new rendering events. If I don't use an "order" object but directly a "selectedProducts" array it works, but I don't want to use this solution. Later I need to pass the order object to other components.

You can make your object like: order: {

        selectedProducts: [],
        key:0
    },

and your template

<product-selector :selected-products="order.selectedProducts" v-model="order" :key="order.key/>

and when you emit the new selected products increment the order key

If you want to make the components 'reactive', you have to emit data up from the child component to the parent component, and then in the parent component, you have to react to the emitted events. You can read more about it in the documentation here: https://v2.vuejs.org/v2/guide/components.html#Using-v-model-on-Components

Pay attention to this part:

For this to actually work though, the inside the component must:

Bind the value attribute to a value prop On input, emit its own custom input event with the new value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM