vue數組和對象不能直接賦值


問題情況:

<Row :key="index"
    v-for="item,index in strategy_level_list"
>
    <Col
        <input :key="index" @input="changeFunc(index, $event)"> 
    >
    </Col>
</Row>
<button @click="addStrategy">增加策略等級</button>


data(){
    return{
        strategy_level_list: [],
        strategy_level_item: { "key": -1 }
    }
},
methods:{
    addStrategy(){
        this.strategy_level_list.push(this.strategy_level_item);
    },
    changeFunc(index, value){
        strategy_level_list[index].key = value;
    }
}

 

上述代碼會導致:每次更改input框中的內容時,所有input框的value都會同步改變

 

問題原因:

Vue不能檢測以下變動的數組: 

  當你利用索引直接設置一個項時,例如:vm.items[indexOfItem] = newValue

  當你修改數組的長度時,例如:vm.items.length = newLength

  當第一種情況需求時,可以使用this.$set(this.arr,index,newVal)

Vue不能檢測對象屬性的添加和刪除:

  可以使用this.$set(this.person,'age',12)

     當需要添加多個對象時,Object.assign({},this.person,{age:12,name:'wee'})

 

 

解決方法:

將changFunc中的代碼修改成

changeFunc(index, value){
    let newVal = { "key":value };
    this.$set(this.strategy_level_list, index, newVal);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM