Vue.set( target, key, value )

 <!-- 
        Vue.set( target, key, value )
        向响应式的对象中添加属性
        vue 实例data中的对象,直接添加属性,this.obj.property = '' ,虽然对象上添加了该属性,但是view上不会显示改变
        this.$set(obj, property ,value) 可以达到想要的效果(这里的this指的是vue实例

     -->
    <div id="app">
        <ul>
            <li v-for="(pro , key ,index) in superman">
                {{pro}} --- {{key}} --- {{index}}
            </li>
        </ul>
        <button @click="addpro">添加属性</button>
    </div>

    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                superman: {
                    name: 'sm',
                    age: 98,
                    sex: 'male'
                }
            },
            methods: {
                addpro: function(){
                    this.superman.city = 'beijing' //页面上不会显示 city --- beijing --- 3

                    // this.$set(this.superman, 'city', 'beijing') //使用$set()方法

                    console.log(this.superman);
                    
                }
            }


        })
    </script>
 

猜你喜欢

转载自my.oschina.net/u/3229305/blog/1819129