watch (观察者)
import { createComponent, watch, reactive } from '@vue/composition-api'
export default createComponent({
setup() {
// 观察reactive
const state = reactive({ count: 0 })
watch(
() => state.count,
(count, prevCount) => {
console.log(count)
console.log(prevCount)
}
)
setTimeout(() => {
state.count++
}, 1000)
})
</script>
<script>
export default createComponent({
setup() {
const fooRef = ref(0)
const barRef = ref(0)
watch([fooRef, barRef], (currArr, prevArr) => {
console.log(currArr, 'newValue')
console.log(prevArr, 'oldValue')
})
// or
watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
/****/
})
setTimeout(() => {
fooRef.value++
barRef.value++
* [1,1] "newValue"
*/
}, 1000)
}
})
</script>
<script>
import { createComponent, watch, ref } from '@vue/composition-api'
export default createComponent({
setup() {
const count = ref(0)
// 第一次执行不会打印
watch(count, value => console.log(value), { lazy: true })
setTimeout(() => {
count.value++
// -> logs 1
}, 1000)
}
</script>