- 方法methods只要调用每次都会执行
- watch(惰性)只有依赖项更新才会执行回调函数,且组件初次渲染不会执行
- watchEffect:自动追踪依赖变化,只要依赖更新即执行回调函数,且组件初次渲染即执行回调函数
- computed(惰性): 返回一个只读的ref,具有缓存功能,只有依赖项更新才执行回调函数,且组件初次渲染即执行回调函数
<template><section class="demo-wrap"><el-button @click="handleClick">{{ state.count }}</el-button><h1>{{ msg }}</h1><el-button @click="handleNameClick">{{ name }}</el-button></section>
</template><script setup>
import { ref, reactive, computed, watch, watchEffect } from 'vue'const state = reactive({ count: 0 })const text = ref('i am 20 years old !')const name = ref('Eason')
const handleClick = () => {state.count++name.value = `Hello - ${Math.random()}`text.value = 'Beijing'
}const handleNameClick = () => {name.value = 'Christina'console.log('changed name is: ', name.value)
}
watch(() => state.count, (val, preVal) => {console.log('val is :', val)console.log('preVal is :', preVal)
})
watch(text, (val, preVal) => {console.log('val is: ', val)console.log('preVal is: ', preVal)
})
watch([text, name], ([text, name], [preText, preName]) => {console.log('new val: ', text, name)console.log('old val: ', preText, preName)
})
watchEffect(() => {const changedName = name.valueconsole.log(`name has changed to ${changedName}`)
})
const stop = watchEffect(() => {})
stop()
const msg = computed(() => {return text.value.toUpperCase()
})</script>