vue watcheffect
时间: 2023-09-14 17:02:26 浏览: 105
Vue's `watchEffect` is a reactive function that watches for changes in reactive properties and executes a callback function when a change occurs. It is similar to Vue's `computed` property, but instead of returning a value, it directly executes a function.
The `watchEffect` function takes in a callback function that contains the reactive properties that you want to watch. When any of these properties change, the callback function is executed. Vue automatically tracks all the reactive properties used in the callback function and only executes it when necessary.
Here's an example of using `watchEffect`:
```
<template>
<div>
<h1>Count: {{ count }}</h1>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { watchEffect, reactive } from 'vue'
export default {
setup() {
const state = reactive({
count: 0
})
const increment = () => {
state.count++
}
watchEffect(() => {
console.log(`Count has changed to ${state.count}`)
})
return {
count: state.count,
increment
}
}
}
</script>
```
In this example, we're using `watchEffect` to log a message to the console whenever the `count` property changes. We're also using Vue's `reactive` function to create a reactive state object that contains the `count` property. When the `increment` function is called, it increases the `count` property, which triggers the `watchEffect` callback function.
Note that we're returning the `count` and `increment` variables from the `setup` function so that they can be used in the template. Vue's `reactive` function and `watchEffect` are part of the Composition API, which is a new way of writing Vue components introduced in Vue 3.
阅读全文