如何解决vuejs不能把后面增加、改动的元素渲染出来

https://jsfiddle.net/5uvo11w3/

我点addOne后仍旧还是展示原来的

<div id="container">
<h1 v-for="(item, key) in items" >
  {{ key }}
</h1>

<div type="buttom" v-on:click="addOne">addOne</div>
<div type="buttom" v-on:click="consoleLog">consoleLog</div>

</div>


<script>
new Vue({
  el: '#container',
  data: {
    items: {
       "tube1":[
           {"msg": "hello"},
           {"msg": "world"},
       ],
       "tube2":[
           {"msg": "hello2"},
           {"msg": "world2"},
       ],
       "tube3":[
           {"msg": "hello3"},
           {"msg": "world3"},
       ]
    }
  },
  methods:{
       addOne: function(){
               this.items["tube4"] = [
           {"msg": "hello4"},
           {"msg": "world4"},
               ];
       },
       consoleLog: function(){
               console.log(this.items)
       }
  }
})
</script>
阅读 2.9k
1 个回答

这样写vue是检测不到变化的,可以通过vue.set设置。

把addOne方法改写为这样

 addOne: function(){
          var arr = [
               {"msg": "hello4"},
               {"msg": "world4"},
             ];
             this.$set(this.items,"tube4",arr);
       }
       

原理参考深入响应式原理

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题