Vuejs通过参考更新v-for

时间:2018-08-21 22:03:01

标签: vue.js vuejs2

所以我有一个简单的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 on的结果),而不是更新该结果的v-for引用,所以当结果更改为时,如何更新结果的v-for引用请注意,由于css的设计,我无法将v-for放在其中,它需要与

  • ...

    分开
  • 1 个答案:

    答案 0 :(得分:0)

    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>
    
    相关问题