有没有一种方法可以在v-for循环中观察输入(v-model) ?

is there a way to watch inputs (v-model) in a v-for loop

本文关键字:循环 观察 输入 v-model v-for 一种 方法 有没有      更新时间:2023-09-26

我有一个对象数组,我循环遍历,我想观察与每个对象相关的输入,但问题是v-model="something":这个东西改变了,所以我不知道该看什么

<table class="table displaynone" id="table-sauces" >
    <tr v-for="o in order">                          
        <td>@{{o.produit}} @{{o.num}}</td>
            <td v-for="sauce in les_sauce">                  
                <input type="radio" :name="o.produit+o.num" @click="$emit(setsauce(o.is_menu))" :value="sauce.id" v-model="o.sauce">  
                  @{{sauce.name}}
                <img :src="sauce.link">
        </td>
    </tr>   
</table>

如何查看输入的值

你有两个层次的循环,它们似乎在不同的东西上循环(orderles_sauce)。

尽管如此,这里有一个简化的示例,它使用了代码的内循环(v-for="sauce in les_sauce"),并展示了如何监视更改:

你可以为每一个数组项创建一个单独的子组件,并观察子组件内部的变化。

例如,这是父组件模板中的循环部分:

<td v-for="sauce in les_sauce">
    <sauce-view :sauce="sauce" :ord="o"></sauce-view>
</td>

和子组件:

Vue.component('sauce-view', {
    props: ["sauce", "ord"],
    template: `
        <div class="sauce-view">
            <input type="radio" :name="ord.produit+ord.num"
            @click="$emit(setsauce(ord.is_menu))"
            :value="sauce.id" v-model="ord.sauce">  @{{sauce.name}}
            <img :src="sauce.link">
        </div>`,
    watch: {
        sauce: function() {
            // this will get triggered within sauce-view component, when one of your "sauce" changes
        },
        ord: function() {
            // this will get triggered within sauce-view component, when one of your "o" changes
        }
    }
})

正如上面子组件代码的示例代码所示,在这里您可以查看来自父组件的单个数组项—osauce

注意:父组件中的o作为ord传递给子组件。这个例子展示了父组件和子组件中的变量不需要相同。

编辑:注释#4(深度观察)后的附加信息

在上面的示例代码中,我没有设置监视深度所需的deep:true

以下是API文档中的相关行:

选择:深

为了检测对象内部嵌套的值变化,你需要在options参数中传入deep: true。

在您的示例中,您可以按如下方式修改上面的示例代码:

watch: {
    sauce: {
        handler: function() {
            // this will get triggered when any of the nested values of "sauce" change
        },
        deep: true  // this enables watching the nested values inside this object 
    },
    ord: function() {
        // this will get triggered within sauce-view component, when one of your "o" changes
    }
}

希望有帮助!