前言
watch
函数监听当某个值的改变,可以就此做一些事情(钩子函数)
监听ref对象
<body>
<div id="app">
<input v-model="firstName"/>
<input v-model="lastName"/>
<div>{{fullName}}</div>
</div>
</body>
<script>
const {createApp, ref, watch} = Vue;
const firstName = ref('');
const lastName = ref('');
let fullName = ref('');
const app = {
// 入口函数
setup() {
// 监听ref对象
watch(firstName, (newVal, oldVal) => {
fullName.value = firstName.value + lastName.value;
})
// 监听ref对象
watch(lastName, (newVal, oldVal) => {
fullName.value = firstName.value + lastName.value;
})
return {
firstName,
lastName,
fullName
}
}
}
// 挂载(建立vue与dom的联系)
createApp(app).mount('#app')
</script>
监听reactive对象
<body>
<div id="app">
<input v-model="name.firstName"/>
<input v-model="name.lastName"/>
<div>{{fullName}}</div>
</div>
</body>
<script>
const {createApp, ref, reactive, watch} = Vue;
const name = reactive({
firstName: '',
lastName: ''
})
let fullName = ref('');
const app = {
// 入口函数
setup() {
// 监听reactive对象
watch(name, (newVal, oldVal) => {
fullName.value = name.firstName + name.lastName;
})
return {
fullName,
name
}
}
}
// 挂载(建立vue与dom的联系)
createApp(app).mount('#app')
</script>
监听reactive对象下的单个属性
<body>
<div id="app">
<input v-model="name.firstName"/>
<input v-model="name.lastName"/>
<div>{{fullName}}</div>
</div>
</body>
<script>
const {createApp, ref, reactive, watch} = Vue;
const name = reactive({
firstName: '',
lastName: ''
})
let fullName = ref('');
const app = {
// 入口函数
setup() {
// 监听reactive对象下的单个属性
watch(()=>name.firstName, (newVal, oldVal) => {
fullName.value = name.firstName + name.lastName;
})
return {
fullName,
name
}
}
}
// 挂载(建立vue与dom的联系)
createApp(app).mount('#app')
</script>