1.生命周期也写在setup里面
setup执行的时间比beforeCreate还要早
所以vue3.x组合式API里面没有创建之前和创建之后(beforeCreate和created钩子)
setup() { // 生命周期也写在setup里面 // setup执行的时间比beforeCreate还要早 // 所以vue3.x组合式API里面没有创建之前和创建之后(beforeCreate和created钩子) const num = ref(10); // 挂载完成之后 onMounted(() => { console.log('挂载完成了', document.getElementById('test')) }) onUpdated(() => { console.log('更新了') }) return { num, }; },
2.toRef的使用
toRef是一个工具型函数,实现响应式
具体使用如下
setup(){
// person是响应式数据
const person = reactive({
name: 'zs',
age: '20'
})
// const age = person.age //这是一个值,不是响应式数据
// toRef可以把响应式数据里的某个属性变成响应式的数据
const age = toRef(person, 'age')
return {
person,
age
}
}
3.torefs
toRefs可以把对象中的每个属性都变成响应式的,并且与原来的响应式数据关联
具体代码如下
setup(){
const person = reactive({
name: 'zs',
age:'20'
})
// toRefs可以把对象中的每个属性都变成响应式的,并且与原来的响应式数据关联
// const obj = toRefs(person)
return {
person,
// ...obj,
...toRefs(person)
// 可以直接写成
// ...person ,//模板中可以使用,但不是响应式的
}
}
4.provide和inject
provide和inject用于组件通信,具体使用步骤如下
父组件
<template>
<div class="boxfather">
{
{age}}
<child></child>
</div>
</template>
<script>
import child from "./components/child02.vue";
import { provide, ref } from "vue";
export default {
name: "boxfather",
components: {
child,
},
setup() {
// 想子组件提供数据
const age = ref(20) //当传的是响应式对象时,
provide("age", age);
provide("name", "zs");
return {
age
};
},
};
</script>
<style>
.boxfather {
padding: 30px;
background-color: #eee;
}
</style>
子组件
<template>
<div class="children">
<button @click="age++">{
{age}}</button>
<button>{
{name}}</button>
</div>
</template>
<script>
import { inject } from 'vue'
export default {
name: 'children',
setup(){
// 接收父组件传过来的数据
const age = inject('age') //这里不能实现响应式,
// 是因为父组件传过来的是值,不是响应式的数据
// 当父组件传过来的是响应式数据时,就可以改变数据了,
// 并且和父组件的数据是相关联的
const name = inject('name')
return {
age,
name
}
}
}
</script>
<style>
.children {
padding: 30px;
background-color: pink;
}
</style>