vue中對象和數組無法雙向綁定的情況以及解決方案

1. 修改數組中的內容,數組發生了改變,而頁面沒有發生改變。

解決方案是通過$set方法來設置數組的值,該方法有三個參數,第一個是要被設置值的目標對象,第二個是設置值在數組中的索引,第三個是設置的值

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <style type="text/css">
            [v-cloak]{
                display: none;
            }
        </style>
    </head>
    <body>
        <div id="app" v-cloak>
            <div v-for="item in testArr">
                {{item}}
            </div>
            <button @click="click1">點擊1</button>
            <button @click="click2">點擊2</button>
        </div>
            
    </body>
    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>
    <script>
        window.vm = new Vue({    
            el:'#app',
            data:{
                testArr : [1,2,3]
            },
            methods:{
                click1:function(){
                    console.log("修改第一個數字,頁面沒有修改");
                    this.testArr[0] = this.testArr[0]+1;
                },
                click2:function(){
                    console.log("修改了數字,頁面發生了修改");
                    vm.$set(this.testArr,0, this.testArr[0]+1);
                }
            }
        })
    </script>
</html>

2. 修改對象的屬性,但是頁面的值沒有發生改變。

導致這種情況的原因是:在vue對象的data中沒有設置對象的屬性。

解決方法:一。直接在vue的data中設置無法雙向綁定的屬性。

     二。使用$set來設置屬性。

解決方法一適用於在頁面加載前就清楚對象包含哪些屬性值。但往往有的時候,數據是通過ajax拿到的,並不清楚要綁定的屬性名稱,這時候更適合使用方法二。

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        
        <div id="app">
            {{test1.name}}
            <br />
            <button @click="click1">點擊添加屬性</button>
            <button @click="click2">使用$set添加屬性</button>
        </div>
            
    </body>
    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>
    <script>
        
        window.vm = new Vue({
            
            el:'#app',
            data:{
                test1:{
                    // name : ''    解決方案一:直接初始化屬性
                }
            },
            methods:{
                click1:function(){
                    this.test1.name = "小明";
                    console.log("屬性添加失敗,原因是test1的name屬性沒有預先初始化");
                },
                click2:function(){
                    // 解決方案二:使用$set來解決
                    vm.$set(this.test1,"name","小明");
                    console.log("屬性添加成功");
                }
            }
        })
    </script>
</html>

 

發佈了13 篇原創文章 · 獲贊 14 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章