Composition API
setup函数
在旧的 beforeCreate 钩子函数之后和 created 的钩子函数之前立即调用 setup 方法。因此,我们不再需要这两个钩子,我们可以简单地将本应有的代码放在 setup() 方法中。
setup 函数是一个新的组件选项。作为在组件内使用 Composition API 的入口点。
setup会在 beforeCreate前被调用,同时在vue3中setup代替了beforeCreate和created
网上许多文章认为setup执行时间在beforeCreate 和created 之间但试验结果setup是在beforeCreate之前行调用.
- setup有两个参数 props和context
- props 接收当前组件props选项的值,即获取父组件传递过来的参数
- context,接收一个上下文对象,该对象中包含了一些在vue 2.x 中需要通过 this 才能访到属性
<script>
import {defineComponent } from 'vue';
export default defineComponent({
props: {
name: String
},
setup(props, context) {
context.attrs;
console.log(props.name);
context.slots;
context.emit;
}
});
</script>
生命周期钩子
除去 beforeCreate 和 created 之外,在我们的 setup 方法中,有9个旧的生命周期钩子,我们可以在setup 方法中访问
beforeCreate -> use setup()
created -> use setup()
其中setup函数是整合 created跟 beforeCreat
beforeMount ->onBeforeMount (挂载前)
mounted -> onMounted (挂载后)
beforeUpdate -> onBeforeUpdate**(更新前)**
updated -> onUpdated (更新后)
beforeDestroy -> onBeforeUnmount ( 销毁前)
destroyed ->onUnmounted ( 销毁后)
以解构赋值的方式即可引入
import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onActivated, onDeactivated, onErrorCaptured } from 'vue'
export default {
setup() {
onBeforeMount(() => {
// ...
})
onMounted(() => {
// ...
})
onBeforeUpdate(() => {
// ...
})
onUpdated(() => {
// ...
})
onBeforeUnmount(() => {
// ...
})
onUnmounted(() => {
// ...
})
onActivated(() => {
// ...
})
onDeactivated(() => {
// ...
})
onErrorCaptured(() => {
// ...
})
}
}
如何理解Vue3 跟 Vue2的数据响应结构
在Vue3 中 method 跟 data 数据已经被setup函数集成了
setup是集成性api
我们想要创建数据 则需要引入类型
import { reactive, ref, } from 'vue'; //全部函数以es6 语法 进行获取提升性能优化
//reactive 处理的是复杂数据类型 json /array
//ref 定义简单类型的数据 number/string
export default {
setup() {
//setup 集成性api 所有生命周期函数 可在里面使用
const state = reactive({
username: '1111',
password: '',
});
const number = ref(1);
// ref 本质上还是reactive 但是简单数据类型会在传参数后 创建一个函数
// 在函数中以value中获取 如number.value 获取
console.log('我是setup');
return {
state,
number,
};
},
};
</script>
reactive注意点:
reactive传递的参数必须是object/array.
如果传递了其他的对象,默认情况下修改对象,界面不会自动更新,如果想要更新,可以通过重新赋值的方式。
ref注意点:
ref的本质其实还是reactive,当我们给ref函数传递一个值之后,ref
函数会自动的转化成{value: xx},只是中间自动帮我们套了一层value
const name = ref(1) => name: {value: 1}
所以当我们修改值时,name.value = ‘xxx’,此时才能进行响应式更新.