源頭
最近在使用vue開發(fā)H5的項目前端的時候,遇見了動態(tài)增加下拉框選項,vue無法回顯的問題。
現(xiàn)象
<template>
<div style="border:1px solid pink;padding:30px 300px 30px 30%;">
<span>{{ selectData.tip }}</span>
<el-select v-model="selectData.value" clearable placeholder="請選擇">
<el-option
v-for="item in selectData.options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
<el-button type="success" @click="addOptionContent">增加下拉框選項</el-button>
</div>
</template>
<script>
export default {
components: {
},
name: "test",
data() {
return {
selectData: {
tip: "下拉框選項:",
value: "",
options: [
{ value: '0', label: '雙皮奶' },
{ value: '1', label: '蚵仔煎' },
{ value: '2', label: '龍須面' },
{ value: '3', label: '北京烤鴨' }
]
}
};
},
watch: {},
mounted() {},
beforeCreate() {},
created() {},
methods: {
addOptionContent() {
this.selectData.options[4] = { value: '4', label: '潮汕火鍋' };
console.log(this.selectData.options);
}
},
};
</script>
<style scoped></style>
效果:

使用this.$set解決問題
addOptionContent() {
this.$set(this.selectData.options, 4, { value: '4', label: '潮汕火鍋' })
console.log(this.selectData.options);
}
效果:

Vue中=賦值為啥不生效
官方解釋:向響應式對象中添加一個屬性,并確保這個新屬性同樣是響應式的,且觸發(fā)視圖更新。它必須用于向響應式對象上添加新屬性,因為 Vue 無法探測普通的新增屬性
結(jié)論
Vue 不允許在已經(jīng)創(chuàng)建的實例上動態(tài)添加新的根級響應式屬性。如果動態(tài)添加新的響應式屬性使用this.$set