您当前的位置: 首页 >  彭世瑜

Vue重新渲染数据

彭世瑜 发布时间:2019-10-09 22:56:29 ,浏览量:1

Vue 不能检测以下数组的变动: 1、当你利用索引直接设置一个数组项时 2、当你修改数组的长度时 3、对象属性的添加或删除

来源: https://cn.vuejs.org/v2/guide/list.html

代码引入vue



通过索引赋值,修改数组后没有检测到变化


    
        {{color}}
    



    var app = new Vue({
        el: "#app",

        data(){
            return {
                colors: ["red", "black", "green", "yellow", "blue"]
            }
        },

        methods:{
            changeItem(index){
                this.colors[index] = "white";

                console.log(this.colors[index]);
            }
        }
    })
 
方案一

通过v-if="isShow" 更新



    
        {{color}}
    



    var app = new Vue({
        el: "#app",

        data(){
            return {
                isShow: true,

                colors: ["red", "black", "green", "yellow", "blue"]
            }
        },

        methods:{
            changeItem(index){
                this.colors[index] = "white";

                console.log(this.colors[index]);

                // 重新渲染数据
                this.isShow= false

                // 更新dom
                this.$nextTick(()=>{
                    this.isShow = true
                })
            }
        }
    })
  
方案二

key 值变更时,会自动的重新渲染



        
        {{color}}
    



    var app = new Vue({
        el: "#app",

        data(){
            return {
                colorsKey: 0,

                colors: ["red", "black", "green", "yellow", "blue"]
            }
        },

        methods:{
            changeItem(index){
                this.colors[index] = "white";

                console.log(this.colors[index]);
                // 触发渲染
                this.colorsKey++;
            }
        }
    })
    

参考 vue 强制组件重新渲染(重置)

关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 1浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0794s