关于前端:vue修改属性值后页面不重新渲染

6次阅读

共计 1144 个字符,预计需要花费 3 分钟才能阅读完成。

优先举荐应用 vue 的 $set 赋值,能够参考 vue 的官网文档 $set 用法。
如果不行能够应用 this.$forceUpdate() 办法

最近遇到几次批改了对象的属性后,页面并不从新渲染,场景如下:

HTML 页面如下:

<template  v-for="item in tableData">
              <div :class="{'redBorder':item.red}">
                <div>{{item.name}}</div>
                <div>
                    <el-button size="mini" @click="clickBtn(item.id)" type="info"> 编辑 </el-button>
                      <p class="el-icon-error" v-show="item.tip"></p>
                </div>
              </div>
</template>

js 局部如下:


<script>
 export default {data() {
        return {tableData:[{id:0,name:"lili",red:false,tip:false}]
        }
      },
 
      methods: {clickBtn(id){this.tableData[id].red=true;
        this.tableData[id].tip=true;        
    }
    }
}
</script>

绑定的 class 是加一个红色的边框,如下:


.redBorder{border:1px solid #f00;}

在我的项目中点击 button 后不呈现红色边框和提醒谬误框,关上 debugger 查看,发现运行到了这里却没有执行,tableData 中的值并没有扭转,这个办法在以前应用时会起作用,可能是这次的我的项目比较复杂引起的,具体起因不明。
后通过查找材料批改为应用 $set 来设定批改值,js 如下:

this.$set(this.tableData[id],"red",true);

然而仍然没有起作用,关上 debugger 发现 tableData 的值批改胜利,没有渲染到页面上,查找的材料也是比拟凌乱,并不能解决问题,后求教大神,才晓得是数据档次太多,没有触发 render 函数进行自动更新,需手动调用,调用形式如下:

this.$forceUpdate();

js 残缺代码如下:


<script>
 export default {data() {
        return {tableData:[{id:0,name:"lili",red:false,tip:false}]
        }
      },
 
      methods: {clickBtn(id){this.$forceUpdate();
        this.$set(this.tableData[id],"red",true);
        this.$set(this.tableData[id],"tip",true);    
 }}}
</script>

如有问题请多指教。

正文完
 0