鍍金池/ 問答/Linux  HTML/ vue 關(guān)于 實例后對已有對象添加新屬性的問題

vue 關(guān)于 實例后對已有對象添加新屬性的問題

1

<div id="app">
  <h2>Todos:</h2>
  <ol>
    <li v-for="todo in todos.list">
      <label>
        <span>
          {{ todo.text }}
        </span>
      </label>
    </li>
  </ol>
</div>

new Vue({
  el: "#app",
  data: {
    todos:{}
  },
  mounted(){
    this.todos.list= [
      { text: "Learn JavaScript" },
      { text: "Learn Vue" },
      { text: "Play around in JSFiddle" },
      { text: "Build something awesome"}
    ]
}
})

結(jié)果如圖:todos的list未渲染出來
圖片描述

我的分析:this.todos.list 是對todos添加新的屬性,這個list屬性未在data里定義,不是響應(yīng)式的。所以視圖不會重新渲染。

但是請看案例2,如下:

2

<div id="app">
  <h2>Todos:{{todos.name}}</h2>   //插入name
  <ol>
    <li v-for="todo in todos.list">
      <label>
        <span>
          {{ todo.text }}
        </span>
      </label>
    </li>
  </ol>
</div>

new Vue({
  el: "#app",
  data: {
    todos:{
      name:'work'  //在data中 todos有個name屬性,但是沒有l(wèi)ist屬性
    }
  },
  mounted(){
    this.todos.name='study'; // name 屬性變更
    this.todos.list= [     // 添加新屬性 list  
      { text: "Learn JavaScript" },
      { text: "Learn Vue" },
      { text: "Play around in JSFiddle" },
      { text: "Build something awesome"}
    ]
}
})

結(jié)果如下圖圖片描述

我的疑問:為什么list未在data中的todos中定義,卻可以渲染出來了

回答
編輯回答
挽青絲

mounted是掛載數(shù)據(jù)完成之后的鉤子
beforeMount是肯定沒有問題 會渲染的

其次第二個是因為你觸發(fā)了data數(shù)據(jù)的更新 賦值了 list數(shù)據(jù)也監(jiān)聽到了 所以渲染

2017年9月29日 14:02