X
XiaoSong
V1
2023/02/07阅读:36主题:默认主题
Vue3使用技巧-监听器
基本示例
当某个数据发生改变后我们希望做一些操作,比如更改dom或是修改一些数据,可以使用
watch
监听器实现。基本案例:
<p>price is: {{ price }}</p>
<input type="text" v-model.lazy="name">
import {ref, watch} from 'vue'
const name = ref('apple')
const price = ref('6299')
watch(name, (newValue, oldValue) => {
console.log(newValue, oldValue) // xiaomi apple
// 当name的值改变后重新设置价格
setPrice(4999)
})
const setPrice = (p) => {
price.value = p
}
以上代码中,使用监听器监听name
值的变化,当改变后进行价格重置操作。注意v-molde
使用了.lazy
修饰符,当我按回车键的时候数据才会改变。
更改前的:
name改为'xiaomi'后 'price'自动改变了
侦听数据源类型
watch
可以监听一个 ref (包括计算属性)、一个响应式对象、一个 getter 函数、或多个数据源组成的数组:
监听单个ref
const name = ref('apple')
const price = ref('6299')
// 监听单个ref
watch(name, (newValue, oldValue) => {
console.log(newValue, oldValue) // apple xiaomi
})
监听getter函数
const num1 = ref(1)
const num2 = ref(2)
// num1或num2改变后自动输出sum
watch(() => num1.value + num2.value, (sum) => {
console.log(sum)
})
多个来源组成的数组
// num1或num2改变就会输出
watch([num1, () => num2.value], (newValue, oldValue) => {
console.log(newValue, oldValue)
})
监听响应式对象
const phone = reactive({name: 'xiaomi'})
// 第一个参数不能直接写phone.name, 而是要写成一个getter函数
watch(() => phone.name, (newValue) => {
console.log(newValue)
})
作者介绍
X
XiaoSong
V1