1.生命周期钩子
setup可以用来代替methods、data、watch等这些选项,也可以替代生命周期钩子。
可以直接导入以on开头的函数注册生命周期钩子;
import {onUpdated,onBeforeUpdate} from "vue"
然后在setup中使用函数即可:
setup() {
onUpdated(()=>{
console.log("updated")
})
}
2.Provide和inject函数
provide给子组件提供数据,一般相邻的组件传递数据使用props,不相邻组件使用provide; inject子组件接受父组件传输过来的数据。
父组件:
<template>
<div>
<home></home>
<button @click="increment">app+1</button>
</div>
</template>
<script>
// 导入provide函数
import {provide,ref,readonly} from "vue";
import Home from "./Home.vue";
export default{
components:{
Home
},
setup() {
const name =ref("phoebe");
const counter = ref(100);
// 将传输数据设置为readonly模式;子组件则不能修改数据
provide("name",readonly(name));
provide("counter",readonly(counter))
// 响应式使counter+1
const increment=()=>{
counter.value++
}
return{
increment
}
}
}
</script>
子组件:
<template>
<div>
<h2>{
{name}} {
{counter}}</h2>
<button @click="homeInrement">home +1</button>
</div>
</template>
<script>
import {inject} from "vue";
export default{
setup() {
// inject 接受传入的数据
const name = inject("name");
const counter =inject("counter")
// 一般情况不能在子组件中使父组件的数据更改,不符合数据的单向传输
// 所以要在父组件中设置传输来的数据为只读模式
const homeInrement = ()=>{counter.value++}
return{
name,
counter,
homeInrement
}
}
}
</script>
3.代码练习
练习1:体会compositionAPI:
将功能模块的代码提取到hook中,方便后期管理和修改;
<template>
<div>
<h2>{
{counter}}</h2>
<h2>{
{doubleCounter}}</h2>
<button @click="increment">+1</button>
<button @click