以下是組件中的資料
data: function () {
return {
sltAreaStyle: {
paddingTop: "3%",
},
checkedTypes: ["krw", "btc", "usdt"],
};
},
下面是checkedTypes資料的觀察功能
watch: {
checkedTypes: {
handler: function (newVal, oldVal) {
if (newVal.length < 1) {
alert("Choose one or more.");
var last = oldVal[0];
this.$data.checkedTypes = [last];
}
},
},
},
下面是我的 html 模板
<div class="ckbxArea">
<input type="checkbox" value="krw" v-model="checkedTypes">KRW</input>
<input type="checkbox" value="btc" v-model="checkedTypes">BTC</input>
<input type="checkbox" value="usdt" v-model="checkedTypes">USDT</input>
</div>
checkedTypes當所有復選框都未選中時,我想將最后一個值更改為資料。如果第一個復選框最終未選中,checkedTypes則將是 'krw' 像checkedTypes = ['krw']The checkedTypesdata is ['krw'],但所有復選框標記都未選中。也就是dom沒有更新。我覺得我不太了解 Vue 的生命周期。我覺得這個問題跟v-model和components的生命周期有關,但是不知道是什么問題。請解釋為什么會出現這個問題并告訴我如何解決它。
uj5u.com熱心網友回復:
嗯,這更多是關于 Vuev-model輸入控制元件的渲染機制。
檢查這個:
- 只有最后一個復選框被選中,因此模型值是
['krw'] - 取消選中最后一個復選框
- 執行觀察者 - 新模型值是
[]但觀察者立即將其設定為與之前相同的值......['krw'] - Vue 重新渲染模板(請參閱控制臺中的訊息)但由于
v-model值與上次渲染時相同,因此不會更新復選框
這種情況的簡單解決方案是使用nextTick將更新推遲到下一個渲染周期
this.$nextTick(() => {
this.checkedTypes = [last];
})
new Vue({
el: "#app",
data: function () {
return {
checkedTypes: ["krw", "btc", "usdt"],
};
},
updated() {
console.log("Component updated")
},
watch: {
checkedTypes: {
handler: function (newVal, oldVal) {
if (newVal.length < 1) {
alert("Choose one or more.");
//console.log("Choose one or more.");
var last = oldVal[0];
// this.checkedTypes = [last];
this.$nextTick(() => {
this.checkedTypes = [last];
})
}
},
},
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.14/vue.js"></script>
<div id="app">
<input type="checkbox" value="krw" v-model="checkedTypes"/> KRW
<input type="checkbox" value="btc" v-model="checkedTypes"/> BTC
<input type="checkbox" value="usdt" v-model="checkedTypes"/> USDT
<pre>{{ checkedTypes }}</pre>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/377658.html
