最近項(xiàng)目在使用vue,遇到幾次修改了對(duì)象的屬性后,頁(yè)面并不重新渲染,場(chǎng)景如下:
HTML頁(yè)面如下:
<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是加一個(gè)紅色的邊框,如下:
.redBorder{ border:1px solid #f00;}在項(xiàng)目中點(diǎn)擊button后不出現(xiàn)紅色邊框和提示錯(cuò)誤框,打開(kāi)debugger查看,發(fā)現(xiàn)運(yùn)行到了這里卻沒(méi)有執(zhí)行,tableData中的值并沒(méi)有改變,這個(gè)方法在以前使用時(shí)會(huì)起作用,可能是這次的項(xiàng)目比較復(fù)雜引起的,具體原因不明。
后通過(guò)查找資料修改為使用$set來(lái)設(shè)定修改值,js如下:
this.$set(this.tableData[id],"red",true);
但是依然沒(méi)有起作用,打開(kāi)debugger發(fā)現(xiàn)tableData的值修改成功,沒(méi)有渲染到頁(yè)面上,查找的資料也是比較凌亂,并不能解決問(wèn)題,后請(qǐng)教大神,才知道是數(shù)據(jù)層次太多,沒(méi)有觸發(fā)render函數(shù)進(jìn)行自動(dòng)更新,需手動(dòng)調(diào)用,調(diào)用方式如下:
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>以上是我解決問(wèn)題的全過(guò)程,有不對(duì)的地方請(qǐng)指教。
這篇vue修改對(duì)象的屬性值后頁(yè)面不重新渲染的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持錯(cuò)新站長(zhǎng)站。
新聞熱點(diǎn)
疑難解答
圖片精選