问题描述:
vue中js修改对象中的属性或修改数组对象中的属性时视图不更新
解决方法:
语法 this.$set(对象, '属性', 重新值)
用法 this.$set( target, key, value )
target:要更改的数据源(可以是对象或者数组)
key:要更改的具体数据
value :重新值
实际场景例子:
<el-col :span="24">
<el-form-item label="缴费日期" prop="chargeTime">
<el-date-picker
v-model="model.chargeTime"
type="date"
placeholder="选择日期"
:picker-options="expireTimeOption"
>
</el-date-picker>
</el-form-item>
</el-col>
<el-col :span="24">
<el-form-item>
<el-button
:autofocus="false"
:class="num == 1 ? 'Cclass' : 'CClass'"
@click="toDay(1)"
>今天</el-button
>
<el-button
:autofocus="false"
:class="num == 2 ? 'Cclass' : 'CClass'"
@click="yesterDay(2)"
>昨天</el-button
>
<el-button
:autofocus="false"
:class="num == 3 ? 'Cclass' : 'CClass'"
@click="beforeYesterday(3)"
>前天</el-button
>
</el-form-item>
</el-col>
<script>
export default {
data() {
// 当天日期之后不能选择的事件
expireTimeOption: {
disabledDate(time) {
return time.getTime() > new Date();
},
},
},
return {
// 缴费日期
chargeTime: [],
num: 0,
rules: {
chargeTime: [
{
required: true,
message: '请录入实际收费日期',
},
],
}
};
},
methods: {
// 把时间 2021-10-31T05:48:21.957Z 格式转化为 2021-10-11 10:00:00
const date = new Date(this.model.chargeTime);
let Y = date.getFullYear();
let M = date.getMonth() + 1;
let D = date.getDate();
if (M < 10) {
M = '0' + M;
}
if (D < 10) {
D = '0' + D;
}
const payDate =
Y + '-' + M + '-' + D + ' ' + '10' +
// 今天点击事件
toDay(index) {
const date = new Date();
this.num = index;
this.$set(this.model, 'chargeTime', date);
},
// 昨天点击事件
yesterDay(index) {
const date = new Date();
date.setTime(date.getTime() - 3600 * 1000 * 24);
this.num = index;
this.$set(this.model, 'chargeTime', date);
},
// 前天点击事件
beforeYesterday(index) {
const date = new Date(
new Date() - 24 * 60 * 60 * 1000 - 24 * 60 * 60 * 1000,
);
this.num = index;
this.$set(this.model, 'chargeTime', date);
},
}
};
</script>
<style lang="scss" scope>
/* 本身样式 */
.CClass {
color: black;
background-color: #dcdfe6;
border: 0px;
}
/* 动态类名点击样式 */
.Cclass {
color: white !important;
background-color: #409eff !important;
}
</style>