关于 onMounted / onUpdated / watchEffect

215 阅读1分钟

onMounted和onUpdated改为watchEffect后报错

错误示例

const x = () => {
    const {width} = selectedItem.value.getBoundingClientRect()
    indicator.value.style.width = width + 'px'
    const {left: left1} = container.value.getBoundingClientRect()
    const {left:left2} = selectedItem.value.getBoundingClientRect()
    const left = left2 - left1
    indicator.value.style.left = left + 'px'
}
// onMounted( x)
// onUpdated(x)
watchEffect(x)

image.png

  • onMounted 是第一次渲染的时候做什么
  • onUpdated 是第一次渲染后每次更新做什么
  • watchEffect 单独用的效果是 onMounted 和 onUpdated 一起用的效果一样的
  • 但是直接用 watchEffect 会有报错,因为 watchEffect 会在第一次渲染之前就执行,那么第一次渲染之后才有的值都会为空,导致错误。

解决办法:在watchEffect外面套一层onMounted

正确示例
onMounted(() => {
    watchEffect(() => {
        const {width} = selectedItem.value.getBoundingClientRect()
        indicator.value.style.width = width + 'px'
        const {left: left1} = container.value.getBoundingClientRect()
        const {left: left2} = selectedItem.value.getBoundingClientRect()
        const left = left2 - left1
        indicator.value.style.left = left + 'px'
    })
})