Vuejs 通过引用更新 v-for



所以我有一个简单的 v-for,v-for 中的每个项目都有一个@click

<result-index>
<li v-for="(result, index) in results" @click="getReult(results[index])">
{{ result.name }}
</li>
</result-index>

现在,我的 getResult 方法只是将该结果分配给结果数据:

methods: {
getResult: function(result) {
// when the child <result-update> updates this, it updates fine, but it doesn't update the v-for reference of this.
this.result = result;
}
}

现在我有另一个组件来获取该结果的数据并显示它:

<result-index>
<li v-for="(result, index) in results" @click="getReult(results[index])">
{{ result.name }}
</li>
<result-update v-if="result" v-model="result">
//... here is a form to access the result and update it
</result-update>
</result-index>

在我的result-update中,我通过indexvalue进行更新,如下所示:

methods: {
update(e) {
this.$emit("input", //data here...);
},
}
watch: {
value: function() {
this.form = this.value;
},
},
created() {
this.form = __.cloneDeep(this.value);
}

哪个更新父结果很好(我们使用@click的那个(,但不是该结果的 v-for 引用,那么当结果发生变化时,我如何更新结果的 v-for 引用,另请注意,由于 css 设计,我无法将 v-for 放在里面, 它需要与...

  • this.result = result时,this.result指向内存的一个地址。

    <result-update v-if="result" v-model="result">接收到输入事件然后将新值分配给this.result时,它将this.result = newValue(实际上指向newValue内存的另一个地址(,因此它不会像预期的那样更改result[index]的值。

    查看下面的演示:

    const test = {result: []}
    let value1 = ['a']
    console.log('org', test)
    test.result = value1 // assign with new array
    console.log('Replace the whole array', test)
    value1[0] = 'b' // assign new value to first element of value1
    console.log('Update one item of the array', test) //test.result and value1 point to same address of the memory

    解决方案:

    您可以保存当前<result-index>的索引,然后按this.results[index]更改该值。

    因此,将您的代码调整到下面,然后应该可以正常工作。

    对于组件<result-index>的模板,将其更改为:

    <result-index>
    <li v-for="(result, index) in results" @click="getReult(index)">
    {{ result.name }}
    </li>
    </result-index>
    

    对于组件<result-index>中的 method=getResult,将其更改为:

    methods: {
    getResult: function(index) {
    this.selected = index;
    }
    }
    

    父组件中,将模板更改为:

    <result-update v-if="selected >= 0" v-model="results[selected]">
    //... here is a form to access the result and update it
    </result-update>
    

    最新更新