一、 Provide提供和Inject 注入
Provide提供
<script setup>
import { provide } from 'vue'
provide(/* 注入名 */ 'message', /* 值 */ 'hello!')
</script>
例如父组件中提供方法
<template>
<div class="home">
dfhualsf
<div>
<button @click="favBtn()">增加</button>
</div>
<A></A>
</div>
</template>
<script setup>
import A from '../components/A.vue';
let num = ref(12)
const favBtn=function(){
num.value=num.value+1
}
provide('homeMethond',num)
</script>
<style lang="scss">
.home {
font-size: 32px;
line-height: 50px;
}
</style>
Inject 注入
<script setup>
import { inject } from 'vue'
const data= inject('message')
</script>
两个子组件中
<template>
<div class="A">
<h1>A组件</h1>
{{num}}
<hr/>
<B></B>
</div>
</template>
<script setup>
import B from './B.vue';
import { inject } from 'vue';
let anum=inject('homeMethond')
</script>
<style lang="scss">
.A {
font-size: 26px;
}
</style>
<template>
<div class="B">
<h1>B组件</h1>
{{bnum}}
</div>
</template>
<script setup>
let bnum=inject('homeMethond')
</script>
<style lang="scss">
.B{
font-size: 26px;
}
</style>
此时当父组件的值发生变化的时候,子组件的也会同步变化
二、 mixins(混入已经不推荐使用了)
1.创建mixins文件夹
2.创建mixins.js文件
import { Ref } from "vue";
export default function(){
let num = ref(1)
let fav=ref(false)
const favBtn=function(){
num.value+=1
fav.value=true
setTimeout(()=>{
fav.value=false
},2000)
}
return {
num,
fav,
favBtn
}
}
父组件
import { Ref } from "vue";
export default function(){
let num = ref(1)
let fav=ref(false)
const favBtn=function(){
num.value+=1
fav.value=true
setTimeout(()=>{
fav.value=false
},2000)
}
return {
num,
fav,
favBtn
}
}
A和B
<template>
<div class="A">
<h1>A组件</h1>
{{fav? '正在计算中':'计算完成'}} {{num}}
<div>
<button @click="favBtn()">增加</button>
</div>
</div>
</template>
<script setup>
import mixins from '../mixins/mixins.js';
let {num,fav,favBtn} =mixins()
</script>
<style lang="scss">
.A {
font-size: 32px;
}
</style>