实现从后台获取数据,并赋值默认值,同时也可以对选框进行更改,即实现双向绑定
1、使用value和on-change方式实现双向绑定,html如下:
<Date-picker
:value="userGetInitTime"
@on-change="handleDatesChange"
:options="userOptions"
confirm
type="datetimerange"
format="yyyy-MM-dd HH:mm:ss"
placeholder="请选择开始时间和结束时间" style="width: 300px;">
</Date-picker>
js:
data(){
return{
userGetInitTime: [], // 获取默认时间
}
}
mounted(){
this.$api.post(USERPORTRAIT1).then(res => {
console.log(res.data)
this.userList = res.data.data_type;
// this.chartList = res.data.graph_type;
this.userForm.userSelectModel = res.data.data_type[2].value;
// 将后台传回的默认时间数据放在时间选择框内
let times = res.data.time.split('/');
let sTime = times[0]; // 按照后台传回的数据,将斜杠前的时间作为初始时间
let eTime = times[1]; // 按照后台传回的数据,将斜杠后的时间作为结束时间
this.userGetInitTime = [new Date(sTime), new Date(eTime)]; // 以new Date()格式将时间放进时间选框
}).catch(res => {
})
},
methods: {
handleUserSubmit(){
this.$refs.userForm.validate( valid => {
if(valid){
const data = {
data_type: this.userForm.userSelectModel,
time: this.userGetInitTime[0]+ '/' + this.userGetInitTime[1],
};
console.log('userGetInitTime',this.time)
this.$api.post(USERPORTRAIT2, data).then(res => {
this.userList = res.data.data_type;
this.userImg = res.data.image;
}).catch(res => {
})
}
})
},
handleDatesChange(array){
this.userGetInitTime = array;
console.log(array);
}
}
2、使用v-model实现双向绑定:
html:
<Date-picker
confirm
v-model="domainGetInitTime"
:options="getDatesOptions"
type="datetimerange"
format="yyyy-MM-dd HH:mm:ss"
placeholder="请选择开始时间和结束时间" style="width: 300px">
</Date-picker>
js:
data() {
return {
domainGetInitTime: [], // 存放后太回传的默认值
}
},
mounted() {
this.$api.post(DOMAIN1).then(res => {
console.log(res.data);
this.domainImage = res.data.image;
this.data_type = res.data.data_type;
this.graph_type = res.data.graph_type;
this.domainForm.domainSelect = res.data.data_type[2].value; // 默认初始化选项
this.domainForm.domainChartSelect = res.data.graph_type[0].value; // 默认初始化选项
// 将后台传回的默认时间数据放在时间选择框内
let times = res.data.time.split('/');
let sTime = moment(times[0], 'YYYY-MM-DD HH:mm:ss').toDate(); // 按照后台传回的数据,将斜杠前的时间作为初始时间
let eTime = moment(times[1], 'YYYY-MM-DD HH:mm:ss').toDate(); // 按照后台传回的数据,将斜杠后的时间作为结束时间
this.domainGetInitTime = [sTime, eTime]; // 以new Date()格式将时间放进时间选框
}).catch(res => {
});
},
methods: {
// 向后台提交请求
handleSubmit() {
this.$refs.domainForm.validate(valid => {
if (valid) {
console.log("domainGetInitTime", this.domainGetInitTime)
const data = {
time: moment(this.domainGetInitTime[0]).format('YYYY-MM-DD HH:mm:ss')+'/'+moment(this.domainGetInitTime[1]).format('YYYY-MM-DD HH:mm:ss'),
data_type: this.domainForm.domainSelect,
graph_type: this.domainForm.domainChartSelect
};
// 根据参数获取后台的值
this.$api.post(DOMAIN2, data).then(res => {
this.data_type = res.data.data_type;
this.graph_type = res.data.graph_type;
this.domainImage = res.data.domain_image
console.log('0000'+res.data.domain_image);
}).catch(res => {
console.log(res)
});
this.$Message.success('Success');
} else {
this.$Message.error('failed');
}
})
},