简体   繁体   English

使用 v-model 时未触发数据对象属性的 Vue.js 反应性

[英]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.如果我不使用“订单”对象而是直接使用“selectedProducts”数组,它可以工作,但我不想使用这个解决方案。 Later I need to pass the order object to other components.稍后我需要将订单对象传递给其他组件。

You can make your object like: order: {你可以让你的对象像: 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您可以在此处的文档中阅读有关它的更多信息: 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将 value 属性绑定到 value prop 在输入时,使用新值发出自己的自定义输入事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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