Skip to content

vue3初学注意点

仲灏2022-01-07约 1 分钟

<div style="display: none;" hidden="true" aria-hidden="true" data-nosnippet>Are you an LLM? You can read better optimized documentation at /pages/a00f46.md for this page in Markdown format</div>

  • 解构会失去响应式功能, 如
js
const foo = {
  x: 0,
  y: 0
}
const { x } = foo
console.log(x) // 0

foo.x = 1
console.log(x) // 0

console.log(foo.x) // 1

image-20220107222750735

当然你后面对数据重新解构是能获取最新的值的

vue
import { toRefs, reactive } from vue
...
setup() {
  const data = reactive({
    count: 0
  })
	const refData = toRefs(data)
  return {
		...refData
	}
}

生命周期

js
// vue2  to vue3

beforeCreate	->	use setup()

created	->	use setup()

beforeMount	->	onBeforeMount

mounted	->	onMounted

beforeUpdate	->	onBeforeUpdate

updated			->		onUpdated

destroyed		->		onUnmounted

activated		->		onActivated

deactivated	->		onDeactivated

errorCaptured	->	onErrorCaptured



// new

onRenderTracked

onRenderTriggerd

watch

  • setup 是和beforeCreate 和 created 一起运行的,而且只执行一次,在后续操作中不会再触发。如果需要出发多次需要引入watch 等函数

  • 如果watch中对单独某个响应式对象中的某个属性进行监听,就需要使用方法返回这个对象的属性,否则你直接写某个属性那么也会失去响应式属性

  • js
    import { watch, reactive } from vue
    ...
    setup() {
      const data = reactive({
        count: 0
      })
      watch([data.count], (newVal, oldVal) => { // 回报如下错误
        ...
      }) 
    }
  • image-20220107225456709

vue
  // 更正后
	watch([() => data.count], (newVal, oldVal) => { 
    ...
  })

defineComponent

defineComponent 这个并没有实现任何逻辑 完全是服务typescript 存在的

新功能

suspens