出于一个功能上的需求,需要给datetime组件一个初始值,通过v-model绑定了数据,,然而datetime里还是空的。
datetime数据没更新
解决办法,刷新组件,通过v-if来创建新的组件
通过v-if刷新组件 通过v-if刷新组件 实现效果
原理
Vue 实现响应式并不是数据发生变化之后 DOM 立即变化,而是按一定的策略进行 DOM 的更新。
$nextTick
是在下次 DOM 更新循环结束之后执行延迟回调,在修改数据之后使用$nextTick
,则可以在回调中获取更新后的 DOM,API 文档中官方示例如下:
new Vue({
// ...
methods: {
// ...
example: function () {
// modify data
this.message = 'changed'
// DOM is not updated yet
this.$nextTick(function () {
// DOM is now updated
// `this` is bound to the current instance
this.doSomethingElse()
})
}
}
})
示例代码 hello-world.vue
<template>
<div>
<div class="info">
<group>
<datetime title="预约日期" v-model="appointment" format="YYYY-MM-DD" required v-if="hackReset"></datetime>
</group>
</div>
<div class="subscribe">
<x-button type="primary" @click.native="submit">提交预约</x-button>
</div>
</div>
</template>
<script>
import { Group, Cell, XButton, XInput, Datetime } from 'vux'
import { getStore, setStore, removeStore } from '@/config/mUtils'
import { setTimeout } from 'timers'
export default {
components: {
Group,
Cell,
XButton,
XInput,
Datetime
},
name: 'subscribe',
data () {
return {
appointment: '',
token: '',
hackReset: true
}
},
created () {
document.title = '填写预约信息'
this.token = getStore('accessToken')
},
mounted () {
this.getTmpImput()
},
methods: {
getTmpImput () {
if(getStore('tmpImput')) {
const tmpImput = JSON.parse(getStore('tmpImput'))
console.log(tmpImput)
this.appointment = tmpImput.appointment
console.log('appointment',this.appointment)
this.hackReset = false
this.$nextTick(() => {
this.hackReset = true
})
removeStore('tmpImput')
}
}
submit () {
//提交处理
},
valdtPhone (numb) {
return /^(1[3-9]\d{9})$/.test(numb)
},
toastMsg (msg) {
this.$vux.toast.show({
type: 'text',
text: msg,
position: 'middle'
})
}
}
}
</script>
<style lang="scss" scoped>
.info {
margin-top: 0.5rem;
}
.subscribe {
margin-top: 0.5rem;
padding: 0.75rem;
}
</style>
网友评论