vue 3.0 最重要的一些新特性,例如 setup() 函数、reactive()、ref() 等这些 Vue Hooks。
1. setup
setup() 函数是 vue3 中,专门为组件提供的新属性。它为我们使用 vue3 的 Composition API 新特性提供了统一的入口。
2. 执行时机
setup 函数会在 beforeCreate 之后、created 之前执行
3. 接收 props 数据
- 在 props 中定义当前组件允许外界传递过来的参数名称:
props: {
p1: String
}
- 通过 setup 函数的第一个形参,接收 props 数据:
setup(props) {
console.log(props.p1)
}
4. context
setup 函数的第二个形参是一个上下文对象,这个上下文对象中包含了一些有用的属性,这些属性在 vue 2.x 中需要通过 this 才能访问到,在 vue 3.x 中,它们的访问方式如下:
const MyComponent = {
setup(props, context) {
context.attrs
context.slots
context.parent
context.root
context.emit
context.refs
}
}
注意:在 setup() 函数中无法访问到 this !!!!
返回和vue2.0的this相同
4. reactive
reactive() 函数接收一个普通对象,返回一个响应式的数据对象
5. reactive
reactive() 函数接收一个普通对象,返回一个响应式的数据对象。
基本语法 等价于 vue 2.x 中的 Vue.observable() 函数,vue 3.x 中提供了 reactive() 函数,用来创建响应式的数据对象,基本代码示例如下:
import { reactive } from '@vue/composition-api'
// 创建响应式数据对象,得到的 state 类似于 vue 2.x 中 data() 返回的响应式对象
const state = reactive({ count: 0 })
6. 定义响应式数据供 template 使用
按需导入 reactive 函数:
import { reactive } from '@vue/composition-api'
在 setup() 函数中调用 reactive() 函数,创建响应式数据对象:
setup() {
// 创建响应式数据对象
const state = reactive({count: 0})
// setup 函数中将响应式数据对象 return 出去,供 template 使用
return state
}
在 template 中访问响应式数据:
<p>当前的 count 值为:{{count}}</p>
7. ref
基本语法 ref() 函数用来根据给定的值创建一个响应式的数据对象,ref() 函数调用的返回值是一个对象,这个对象上只包含一个 **.value **属性:
import { ref } from '@vue/composition-api'
// 创建响应式数据对象 count,初始值为 0
const count = ref(0)
// 如果要访问 ref() 创建出来的响应式数据对象的值,必须通过 .value 属性才可以
console.log(count.value) // 输出 0
// 让 count 的值 +1
count.value++
// 再次打印 count 的值
console.log(count.value) // 输出 1
8. 在 template 中访问 ref 创建的响应式数据
在 setup() 中创建响应式数据:
import { ref } from '@vue/composition-api'
setup() {
const count = ref(0)
return {
count,
name: ref('zs')
}
}
在 template 中访问响应式数据:
<template>
<p>{{count}} --- {{name}}</p>
</template>
!!!注意:新的 ref 会覆盖旧的 ref,示例代码如下:
// 创建 ref 并挂载到 reactive 中
const c1 = ref(0)
const state = reactive({
c1
})
// 再次创建 ref,命名为 c2
const c2 = ref(9)
// 将 旧 ref c1 替换为 新 ref c2
state.c1 = c2
state.c1++
console.log(state.c1) // 输出 10
console.log(c2.value) // 输出 10
console.log(c1.value) // 输出 0