Vue3 watch怎么用
时间: 2023-09-10 08:06:15 浏览: 45
Vue3中,watch的使用与Vue2中略有不同。下面是Vue3 watch的使用方法:
1. 在组件选项中定义一个watch对象。
```
import { watch } from 'vue'
export default {
name: 'MyComponent',
props: {
msg: String
},
setup(props) {
watch(() => props.msg, (newVal, oldVal) => {
console.log('props.msg changed from', oldVal, 'to', newVal)
})
}
}
```
2. 使用watch函数监听一个响应式数据的变化。
```
import { ref, watch } from 'vue'
export default {
name: 'MyComponent',
setup() {
const count = ref(0)
watch(count, (newVal, oldVal) => {
console.log('count changed from', oldVal, 'to', newVal)
})
return {
count
}
}
}
```
3. 可以使用immediate选项来立即执行watch的回调函数。
```
import { ref, watch } from 'vue'
export default {
name: 'MyComponent',
setup() {
const count = ref(0)
watch(count, (newVal, oldVal) => {
console.log('count changed from', oldVal, 'to', newVal)
}, { immediate: true })
return {
count
}
}
}
```
4. 可以使用deep选项来深度监听一个对象或数组的变化。
```
import { reactive, watch } from 'vue'
export default {
name: 'MyComponent',
setup() {
const obj = reactive({ a: 1, b: { c: 2 } })
watch(obj, (newVal, oldVal) => {
console.log('obj changed from', oldVal, 'to', newVal)
}, { deep: true })
return {
obj
}
}
}
```
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)