不管是vue2还是vue3 组件通信方式都很重要 不管是项目还是面试都是经常用到的知识点
一.Vue2组件通信方式回顾
props: 可以实现父子组件 子父组件 甚至兄弟组件通信
自定义事件: 可以实现父子组件通信
全局事件总线$bus:可以实现任意组件通信
pubsub:发布订阅模式 实现任意组件通信
vuex:集中式状态管理器 实现任意组件通信
ref:父组件获取子组件实例vc 获取子组件的响应式数据以及方法
slot:插槽(默认插槽 具名插槽 作用域插槽) 实现父子组件通信...
二.Vue3组件通信方式
2.1props
props可以实现父子组件通信 在vue3中我们可以通过defineProps获取父组件传递的数据 且组件内部不需要引入defineProps方法可以直接使用
父组件给子组件传递数据:
//将info以及money传递给子组件Child
<Child info="我爱祖国" :money="money"></Child>
子组件获取父组件传递的数据_方式一_对象形式(推荐):
let props = defineProps({
info:{
type:String, //接受的数据类型
default:"默认参数",//接受默认数据
},
money:{
type:Number,
default:0
}
})
子组件获取父组件传递数据_方式二_数组形式:
let props = defineProps(["info","money"])
方式一对接受到的数据进行了限制 可以对每个props进行详细配置 接受的数据更加准确 组件稳定
方式二仅能声明接受哪些props 无法进行类型检查和默认值设置 代码更简洁
下面再举一个例子充分说明props的组件通信功能:
//父组件代码如下
<template>
<div class="box">
<h1>props:我是父组件曹操</h1>
<hr />
<!-- 给子组件传递死数据info以及响应式数据money -->
<Child info="我是曹操" :money="money"></Child>
<hr>
<!-- 插值表达式(模板语法)展示响应式数据money -->
<span>{{ money }}</span>
</div>
</template>
<script setup lang="ts">
//props:可以实现父子组件通信,props数据还是只读的!!!
import Child from "./Child.vue";
//导入vue的ref方法用于定义响应式数据 类型vue2中data对象里面声明的属性
import { ref } from "vue";
let money = ref(10000);
</script>
<style scoped>
.box {
width: 100vw;
height: 400px;
background: yellowgreen;
}
</style>
<template>
<div class="son">
<h1>我是子组件:曹植</h1>
<!--调用props对象内的属性不省略的情况--->
<p>{{props.info}}</p>
<p>{{props.money}}</p>
<!--props可以省略前面的名字--->
<p>{{info}}</p>
<p>{{money}}</p>
<!--尝试修改props数据--->
<button @click="updateProps">修改props数据</button>
</div>
</template>
<script setup lang="ts">
//需要使用到defineProps方法去接受父组件传递过来的数据
//defineProps是Vue3提供方法,不需要 引入直接使用
//数组写法接受props
// let props = defineProps(['info','money']);
//对象写法接受props 更加推荐
let props = defineProps({
info: {
type: String,
defaul:"给儿子的信息"
},
money: {
type: Number,
default:0
}
})
//按钮点击的回调 更新Props
const updateProps = () => {
// props.money+=10; //发现不能修改money 因为money是props传过来的 是只读
//[Vue warn] Set operation on key "money" failed: target is readonly.
// console.log(props.info)
}
</script>
<style scoped>
.son{
width: 400px;
height: 200px;
background: hotpink;
}
</style>
2.2自定义事件
在vue框架中事件分为两种: 一种是原生DOM事件 另一种是自定义事件。
原生DOM事件:可以让用户与网页进行交互 比如: click dbclick change mouseenter mouseleave
自定义事件:可以实现子组件给父组件传递数据
下面用一个例子解释自定义事件 创建一个父组件和两个子组件:
//以下两个是子组件1和2
<template>
<div class="son">
<p>我是子组件1</p>
<button>点击我也执行</button>
</div>
</template>
<script setup lang="ts">
</script>
<style scoped>
.son{
width: 400px;
height: 200px;
background: skyblue;
}
</style>
<template>
<div class="child">
<p>我是子组件2</p>
<button @click="handler">点击我触发自定义事件xxx</button>
<button @click="$emit('click','AK47','J20')">点击我触发自定义事件click</button>
</div>
</template>
<script setup lang="ts">
//利用defineEmits方法返回函数触发自定义事件
//defineEmits方法不需要引入直接使用
let $emit = defineEmits(['xxx','click']);
//按钮点击回调
const handler = () => {
//第一个参数:事件类型 第二个|三个|N参数即为注入数据
$emit('xxx','东风导弹','航母');
};
</script>
<style scoped>
.child {
width: 400px;
height: 200px;
background: pink;
}
</style>
<template>
<div>
<h1>事件</h1>
<!-- 原生DOM事件 -->
<pre @click="handler">
大江东去浪淘尽,千古分流人物
</pre>
<!-- 原生DOM事件中自带的事件对象$event -->
<button @click="handler1(1,2,3,$event)">点击我传递多个参数</button>
<hr>
<!--
vue2框架当中:将原生DOM事件绑定到组件标签上这种写法的自定义事件,可以通过.native修饰符变为原生DOM事件
vue3框架下面写法其实即为原生DOM事件
vue3:原生的DOM事件不管是放在标签身上、组件标签身上都是原生DOM事件
-->
<Event1 @click="handler2"></Event1>
<hr>
<!-- 绑定自定义事件xxx:实现子组件给父组件传递数据 -->
<Event2 @xxx="handler3" @click="handler4"></Event2>
</div>
</template>
<script setup lang="ts">
//引入子组件
import Event1 from './Event1.vue';
//引入子组件
import Event2 from './Event2.vue';
//事件回调--1
const handler = (event)=>{
//event即为事件对象
console.log(event);
}
//事件回调--2
const handler1 = (a,b,c,$event)=>{
console.log(a,b,c,$event)
}
//事件回调---3
const handler2 = ()=>{
console.log(123);
}
//事件回调---4
const handler3 = (param1,param2)=>{
console.log(param1,param2);
}
//事件回调--5
const handler4 = (param1,param2)=>{
//打印子组件Event2传递过来的参数 '东风导弹','航母'
console.log(param1,param2);
}
</script>
<style scoped>
</style>
2.2.1原生DOM事件
<pre @click="handler">
我是祖国的老花骨朵
</pre>
当前代码级给pre标签绑定原生DOM事件_点击事件 默认会给事件回调注入_event事件对象 当然点击事件像注入多个参数可以按照如下代码操作 但是切记注入的事件对象务必叫做$event
//绑定原生DOM事件时 同时传递多个参数
<div @click="hander1(param1,param2,param3,$event)">我要传递多个参数</div>
在vue3框架click dbclcik change(这类原生DOM事件) 不管是在标签 自定义标签上(组件标签)都是原生DOM事件。(原生DOM事件在哪里都是原生DOM事件)
2.2.2自定义事件
自定义事件可以实现子组件给父组件传递数据 比如在父组件内部给子组件(Event2)绑定一个自定义事件 代码如下:
//在父组件内的代码
<Event2 @xxx="handler3"></Event2>
//在子组件Event2内的代码
<template>
<div>
<h1>我是子组件2</h1>
<button @click="handler">点击我触发xxx自定义事件</button>
</div>
</template>
<script setup lang="ts">
let $emit = defineEmits(["xxx"]);
const handler = () => {
$emit("xxx", "法拉利", "茅台");
};
</script>
<style scoped>
</style>
我们还会发现在script标签之间 使用了defineEmits()方法 此方法是Vue3提供的不需要引入的 直接使用的方法 向defineEmits方法传递一个数组 数组元素即为将来组件需要触发的 自定义事件类型
此方法返回一个$emit方法用于触发自定义事件
通过点击按钮触发原生DOM_click事件 然后在该事件的处理函数中通过$emit函数触发xxx自定义事件 格式: $emit(要出发的自定义事件的名称,params1,params2...) params1 params2...是子组件要传递给父组件的数据
2.2.3要注意的小细节
//注意
<Event2 @xxx="handler3" @click="handler"></Event2>
//正常说组件标签书写@click应该为原生DOM事件,但是如果子组件内部通过defineEmits定义就变为自定义事件了
let $emit = defineEmits(["xxx",'click']); //此时click变为了自定义事件
给子组件绑定事件 本质上是给组件的根节点上绑定了事件
2.3全局事件总线
全局事件总线可以实现任意组件通信,在vue2中可以根据VM和VC关系推出全局事件总线。但是Vue3中没有Vue构造函数 也就没有Vue.prototype 以及组合式API写法没有this 那么在Vue3想实现全局事件的总线功能就有点不现实了 如果想实现Vue3的全局事件总线功能 可以通过mitt插件实现
mitt官方地址: mitt - npm
关于全局事件总线的例子 定义了一个父组件和两个子组件 如下所示:
//bus/index.js 全局事件总线文件如下
const mitt = require("mitt")
//通过调用第三方模块mitt创建全局事件总线对象
const $bus = mitt()
exports default $bus
//子组件1_接受数据的一方
<template>
<div class="child1">
<h3>我是子组件1:曹植</h3>
</div>
</template>
<script setup lang="ts">
//导入全局事件总线对象$bus
import $bus from "../../bus";
//组合式API函数
import { onMounted } from "vue";
//组件挂载完毕的时候,当前组件绑定一个事件,接受将来兄弟组件传递的数据
onMounted(() => {
//通过$bus.on()方法在全局事件总线中充当接受数据的组件
//第一个参数:即为事件类型 第二个参数:即为该事件的回调
$bus.on("car", (car) => {
console.log(car);
});
});
</script>
<style scoped>
.child1 {
width: 300px;
height: 300px;
background: hotpink;
}
</style>
-----------------------------------------------------------------------------------
//子组件2_传递数据的一方
<template>
<div class="child2">
<h2>我是子组件2:曹丕</h2>
<button @click="handler">点击我给兄弟送一台法拉利</button>
</div>
</template>
<script setup lang="ts">
//引入$bus对象
import $bus from '../../bus';
//点击按钮回调
const handler = ()=>{
//通过$bus.emit()方法在全局事件总线中充当发送数据的组件
//参数一是要触发的自定义事件 参数二是要传递的数据
$bus.emit('car',{car:"法拉利"});
}
</script>
<style scoped>
.child2{
width: 300px;
height: 300px;
background: skyblue;
}
</style>
-----------------------------------------------------------------------------------
//父组件
<template>
<div class="box">
<h1>全局事件总线$bus</h1>
<hr />
<div class="container">
<Child1></Child1>
<Child2></Child2>
</div>
</div>
</template>
<script setup lang="ts">
//引入子组件
import Child1 from "./Child1.vue";
import Child2 from "./Child2.vue";
</script>
<style scoped>
.box {
width: 100vw;
height: 400px;
background: yellowgreen;
}
.container{
display: flex;
justify-content: space-between;
}
</style>
2.4v-model
v-model指令可是收集表单数据(数据双向绑定) 除此之外它也可以实现父子组件数据同步。
而v-model本质是利用props[modelValue]与自定义事件(update:modelValue)实现的。
下方代码:相当于给组件Child传递一个props(modelValue)与绑定一个自定义事件update:modelValue 实现父子组件数据同步
<Child v-model="msg"></Child>
在vue3中一个组件可以通过使用多个v-model,让父子组件多个数据同步,下方代码相当于给组件Child传递两个props分别是pageNo与pageSize 以及绑定两个自定义事件 update:pageNo 与pageSize实现父子数据同步
<Child v-model:pageNo="msg" v-model:pageSize="msg1"></Child>
那么v-model是怎么实现数据同步的呢?? 想想怎么实现父子组件数据同步--- props父传子+ 自定义事件子传父 以下为代码实例:
用下面的例子介绍v-model如何实现组件间通信:
//父组件
<template>
<div>
<!-- 展示响应式数据money pageNo pageSize -->
<h1>v-model:钱数{{ money }}{{pageNo}}{{pageSize}}</h1>
<!-- 将text类型的表单与数据info绑定 -->
<input type="text" v-model="info" />
<hr />
<!-- 下面的代码解释了v-model的工作原理 相当于绑定了一个props属性和自定义事件 -->
<!-- <Child :modelValue="money" @update:modelValue="handler"></Child> -->
<!--
v-model组件身上使用
第一:相当有给子组件传递props[modelValue] = 10000
第二:相当于给子组件绑定自定义事件update:modelValue
-->
<Child v-model="money"></Child>
<hr />
<!-- 与Vue2不同的是 Vue3可以向子组件绑定多个v-model实现多组数据同步 -->
<Child1 v-model:pageNo="pageNo" v-model:pageSize="pageSize"></Child1>
</div>
</template>
<script setup lang="ts">
//v-model指令:收集表单数据,数据双向绑定
//v-model也可以实现组件之间的通信,实现父子组件数据同步的业务
//父亲给子组件数据 props
//子组件给父组件数据 自定义事件
//引入子组件
import Child from "./Child.vue";
import Child1 from "./Child1.vue";
import { ref } from "vue";
//将要填入表单的数据info设置为响应式数据
let info = ref("");
//父组件的数据钱数
let money = ref(10000);
//自定义事件的回调
const handler = (num) => {
//将来接受子组件传递过来的数据
money.value = num;
};
//父亲的数据
let pageNo = ref(1);
let pageSize = ref(3);
</script>
<style scoped>
</style>
--------------------------------
//子组件1
<template>
<div class="child">
<!-- modelValue是从父组件那里通过props对象获取到的数据 父组件一变跟着变 -->
<h3>钱数:{{ modelValue }}</h3>
<button @click="handler">父子组件数据同步</button>
</div>
</template>
<script setup lang="ts">
//接受props
let props = defineProps(["modelValue"]);
let $emit = defineEmits(['update:modelValue']);
//子组件内部按钮的点击回调
const handler = ()=>{
//触发自定义事件
$emit('update:modelValue',props.modelValue+1000);
}
</script>
<style scoped>
.child {
width: 600px;
height: 300px;
background: skyblue;
}
</style>
------------------------------
//子组件2
<template>
<div class="child2">
<h1>同时绑定多个v-model</h1>
<button @click="handler">pageNo{{ pageNo }}</button>
<button @click="$emit('update:pageSize', pageSize + 4)">
pageSize{{ pageSize }}
</button>
</div>
</template>
<script setup lang="ts">
let props = defineProps(["pageNo", "pageSize"]);
let $emit = defineEmits(["update:pageNo", "update:pageSize"]);
//第一个按钮的事件回调
const handler = () => {
$emit("update:pageNo", props.pageNo + 3);
};
</script>
<style scoped>
.child2 {
width: 300px;
height: 300px;
background: hotpink;
}
</style>
2.5useAttrs
在Vue3中可以利用useAttrs方法获取组件的属性与事件(包含:原生DOM事件或者自定义事件)
次函数功能类似于Vue2框架中$attars属性与$listeners方法.
比如:在父组件内部使用一个子组件my-button
<my-button type="success" size="small" title="标题" @click="handler"></my-buttion>
子组件内部可以通过useAttrs方法获取组件属性与事件 因此你也发现了 它类似于props,可以接受父组件传递过来的属性与属性值 需要注意如果defineProps接受了某一个属性 useAttrs方法返回的对象身上就没有对应属性与属性值。
<script setup lang="ts">
import {useAttrs} from "vue"
let $attrs = useAttrs()
</script>
下面的例子将解释useAttrs如何实现组件通信:
<template>
<div>
<h1>useAttrs</h1>
<el-button type="primary" size="small" :icon="Edit"></el-button>
<!-- 自定义组件 HintButton 是对element-plus按钮组件的封装 -->
<HintButton type="primary" size="small" :icon="Edit" title="编辑按钮" @click="handler" @xxx="handler"></HintButton>
</div>
</template>
<script setup lang="ts">
//vue3框架提供一个方法useAttrs方法,它可以获取组件身上的属性与事件!!!
//图标组件
import {
Check,
Delete,
Edit,
Message,
Search,
Star,
} from "@element-plus/icons-vue";
import HintButton from "./HintButton.vue";
//按钮点击的回调
const handler = ()=>{
alert(12306);
}
</script>
<style scoped>
</style>
-------------------
//自定义组件HintButton
<template>
<div :title="title">
<el-button :="$attrs"></el-button>
</div>
</template>
<script setup lang="ts">
//引入useAttrs方法:获取组件标签身上属性 与事件
import {useAttrs} from 'vue';
//此方法执行会返回一个包含标签身上的非props获取的属性与属性值组成的对象 $attars
let $attrs = useAttrs();
//万一用props接受title
let props =defineProps(['title']);
//props与useAttrs方法 都可以获取父组件传递过来 的属性与属性值
//♥但是props接受了useAttrs方法就获取不到了 而且useAttrs能够获取到组件身上的事件
console.log($attrs);
</script>
<style scoped>
</style>
2.6ref与$parent
提及到ref可能会想到它可以获取元素的DOM或者获取子组件实例的VC 既然可以在父组件内部通过ref获取子组件实例VC 那么子组件内部的方法与响应式数据父组件可以使用
比如:在父组件挂载完毕获取组件实例 父组件内部代码:
<template>
<template>
<div>
<h1>ref与$parent</h1>
<Son ref="son"></Son>
</div>
</template>
<script setup lang="ts">
import Son from "./Son.vue";
import { onMounted, ref } from "vue";
const son = ref();
onMounted(() => {
console.log(son.value);
});
</script>
但是需要注意 如果想让父组件获取子组件的数据或者方法需要通过defineExpose对外暴露 因为Vue3中组件内部的数据对外"关闭的" 外部不能访问
<script setup lang="ts">
import {ref} from "vue"
//数据
let money = ref(1000)
//方法
const handler = ()=>{
}
defineExpose({
money,
handler
})
</script>
$parent可以获取某一个组件的父组件实例VC 因此可以使用父组件内部的数据与方法 必须子组件内部拥有一个按钮点击获取父组件实例 当然父组件对象数据与方法需要通过defineExpose方法对外暴露
<button @click="handler($parent)">点击我获取父组件实例</button>
下面用一个例子说明 ref与$parent在组件通信中的作用
//父组件的代码如下:
<template>
<div class="box">
<h1>我是父亲曹操:{{money}}</h1>
<button @click="handler">找我的儿子曹植借10元</button>
<hr>
//通过ref向子组件Son传递数据son
<Son ref="son"></Son>
<hr>
<Dau></Dau>
</div>
</template>
<script setup lang="ts">
//ref:可以获取真实的DOM节点,可以获取到子组件实例VC
//$parent:可以在子组件内部获取到父组件的实例
//引入子组件
import Son from './Son.vue'
import Dau from './Daughter.vue'
import {ref} from 'vue';
//父组件钱数
let money = ref(100000000);
//调用ref()获取子组件实例son
let son = ref();
//父组件内部按钮点击回调
const handler = ()=>{
money.value+=10;
//儿子钱数减去10
son.value.money-=10;
son.value.fly();
}
//对外暴露
defineExpose({
money
})
</script>
<style scoped>
.box{
width: 100vw;
height: 500px;
background: skyblue;
}
</style>
----------------------------
//儿子组件Son
<template>
<div class="son">
<h3>我是子组件:曹植{{money}}</h3>
</div>
</template>
<script setup lang="ts">
import {ref} from 'vue';
//儿子钱数
let money = ref(666);
const fly = ()=>{
console.log('我可以飞');
}
//组件内部数据对外关闭的,别人不能访问
//如果想让外部访问需要通过defineExpose方法对外暴露
defineExpose({
money, //这样父组件内部就可以通过son.value.money获取到子组件实例上的money属性了
fly
})
</script>
<style scoped>
.son {
width: 300px;
height: 200px;
background: cyan;
}
</style>
------------------------------
//闺女组件
<template>
<div class="dau">
<h1>我是闺女曹杰{{money}}</h1>
<button @click="handler($parent)">点击我爸爸给我10000元</button>
</div>
</template>
<script setup lang="ts">
import {ref} from 'vue';
//闺女钱数
let money = ref(999999);
//闺女按钮点击回调 $parent就是父组件实例
const handler = ($parent)=>{
money.value+=10000;
$parent.money-=10000;
}
</script>
<style scoped>
.dau{
width: 300px;
height: 300px;
background: hotpink;
}
</style>
2.7provide与inject
provide[提供] inject[注入] vue3提供两个方法provide与inject 可以实现隔辈组件参数传递
provide方法用于提供数据 此方法执行需要传递两个参数 分别提供数据的key与提供数据value
<script setup lang="ts">
import {provide} from "vue"
provide("token","admin_token")
</script>
后代组件可以通过inject方法获取数据 通过key获取存储的数值
<script setup lang="ts">
import {inject} from 'vue'
let token = inject('token');
</script>
下面一个例子解释provide和inject
//爷爷组件
<template>
<div class="box">
<h1>Provide与Inject{{car}}</h1>
<hr />
//下面是儿子组件Child
<Child></Child>
</div>
</template>
<script setup lang="ts">
import Child from "./Child.vue";
//vue3提供provide(提供)与inject(注入),可以实现 隔辈组件 传递数据
import { ref, provide } from "vue";
let car = ref("法拉利");
//祖先组件通过provide()方法给后代组件提供数据
//两个参数:第一个参数就是提供的数据key
//第二个参数:祖先组件提供的数据 类似键值对
provide("TOKEN", car);
</script>
<style scoped>
.box {
width: 100vw;
height: 600px;
background: skyblue;
}
</style>
------------------
//子组件
<template>
<div class="child">
<h1>我是子组件1</h1>
//下面的是孙子组件Child
<Child></Child>
</div>
</template>
<script setup lang="ts">
import Child from './GrandChild.vue';
</script>
<style scoped>
.child{
width: 300px;
height: 400px;
background: yellowgreen;
}
</style>
--------------------------
//孙子组件
<template>
<div class="child1">
<h1>孙子组件</h1>
<!-- 孙子组件从爷爷组件拿来的数据 -->
<p>{{car}}</p>
<button @click="updateCar">更新数据</button>
</div>
</template>
<script setup lang="ts">
import {inject} from 'vue';
//注入祖先组件提供数据
//需要参数:即为祖先提供数据的key
let car = inject('TOKEN'); //通过inject(要获取的值的键)获取数据
const updateCar = ()=>{
car.value = '自行车'; //获取到的都是响应式数据 所有要用car.value
}
</script>
<style scoped>
.child1 {
width: 200px;
height: 200px;
background: red;
}
</style>
2.8pinia
pinia也是集中式状态容器 类似于vuex 但是核心概念没有mutation modules 使用方式参照官网
pinia官网: Pinia
下面介绍Pinia在组件间通信的作用:
//程序入口 index.vue
<template>
<div class="box">
<h1>pinia</h1>
<div class="container">
<Child></Child>
<Child1></Child1>
</div>
</div>
</template>
<script setup lang="ts">
import Child from "./Child.vue";
import Child1 from "./Child1.vue";
//vuex:集中式管理状态容器,可以实现任意组件之间通信!!!
//核心概念:state、mutations、actions、getters、modules
//pinia:集中式管理状态容器,可以实现任意组件之间通信!!!
//核心概念:state(数据管理)、actions(逻辑操作)、getters(计算属性)
//pinia写法:选择器API、组合式API
</script>
<style scoped>
.box {
width: 600px;
height: 400px;
background: skyblue;
}
.container{
display: flex;
}
</style>
------------------------------------------
//使用pinia模块的createPinia方法创建pinia的主仓库
import createPinia from {"pinia"}
let store = createPinia()
//对外暴露 安装仓库
exports default store
-------------------------------------------
// 使用defineStore(仓库名称,仓库配置对象)创建子仓库 info.ts
//定义info小仓库
import { defineStore } from "pinia";
//第一个仓库:小仓库名字 第二个参数:小仓库配置对象
//defineStore方法执行会返回一个函数,函数作用就是让组件可以获取到仓库数据
let useInfoStore = defineStore("info", {
//存储数据:state 和Vuex不同的是 通过回调函数的返回值书写
state: () => {
return {
count: 99,
arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
},
actions: {
//注意:函数没有context上下文对象
//没有commit、没有mutations去修改数据
updateNum(a: number, b: number) {
this.count += a; //这里的this就是infoStore仓库对象
}
},
getters: {
total() {
let result:any = this.arr.reduce((prev: number, next: number) => {
return prev + next;
}, 0);
return result;
}
}
});
//对外暴露方法
export default useInfoStore;
-------------------------------------------
//子仓库 todo.ts
//定义组合式API仓库
import { defineStore } from "pinia";
import { ref, computed,watch} from 'vue';
//创建小仓库
let useTodoStore = defineStore('todo', () => {
let todos = ref([{ id: 1, title: '吃饭' }, { id: 2, title: '睡觉' }, { id: 3, title: '打豆豆' }]);
let arr = ref([1,2,3,4,5]);
const total = computed(() => {
return arr.value.reduce((prev, next) => {
return prev + next;
}, 0)
})
//务必要返回一个对象:属性与方法可以提供给组件使用
return {
todos,
arr,
total,
updateTodo() {
todos.value.push({ id: 4, title: '组合式API方法' });
}
}
});
export default useTodoStore;
-------------------------------------------
//子组件Child
<template>
<div class="child">
<h1>{{ infoStore.count }}---{{infoStore.total}}</h1>
<button @click="updateCount">点击我修改仓库数据</button>
</div>
</template>
<script setup lang="ts">
import useInfoStore from "../../store/modules/info";
//获取小仓库对象
let infoStore = useInfoStore();
console.log(infoStore);
//修改数据方法
const updateCount = () => {
//仓库调用自身的方法去修改仓库的数据
infoStore.updateNum(66,77);
};
</script>
<style scoped>
.child {
width: 200px;
height: 200px;
background: yellowgreen;
}
</style>
-------------------------------
子组件Child1
<template>
<div class="child1">
{{ infoStore.count }}
<p @click="updateTodo">{{ todoStore.arr }}{{todoStore.total}}</p>
</div>
</template>
<script setup lang="ts">
import useInfoStore from "../../store/modules/info";
//获取小仓库对象
let infoStore = useInfoStore();
//引入组合式API函数仓库
import useTodoStore from "../../store/modules/todo";
let todoStore = useTodoStore();
//点击p段落去修改仓库的数据
const updateTodo = () => {
todoStore.updateTodo();
};
</script>
<style scoped>
.child1 {
width: 200px;
height: 200px;
background: hotpink;
}
</style>
2.9slot
插槽: 默认插槽 具名插槽 作用域插槽 可以实现父子组件通信
2.9.1默认插槽: 在子组件内部的模板中书写slot全局组件标签
<template>
<div>
<slot></slot>
</div>
</template>
<script setup lang="ts">
</script>
<style scoped>
</style
在父组件内部提供解构: Todo即为子组件 在父组件内部使用的时候 在双标签内部书写结构传递给子组件
注意: 开发项目的时候默认插槽一般只有一个
<Todo>
<h1>我是默认擦超填充的解构</h1>//将h1结构传递给子组件Todo
</Todo>
2.9.3具名插槽: 带有名字在组件内部留多个指定名字的插槽
<template>
<div>
<h1>todo</h1>
<slot name="a"></slot>
<slot name="b"></slot>
</div>
</template>
<script setup lang="ts">
</script>
<style scoped>
</style>
父组件内部向指定的具名插槽传递结构 要注意:v-slot可以替换为#
<template>
<div>
<h1>slot</h1>
<Todo>
<template v-slot:a> //可以用#a替换
<div>填入组件A部分的结构</div>
</template>
<template v-slot:b>//可以用#b替换
<div>填入组件B部分的结构</div>
</template>
</Todo>
</div>
</template>
<script setup lang="ts">
import Todo from "./Todo.vue";
</script>
<style scoped>
</style>
2.9.3作用域插槽
作用域插槽:可以理解为 子组件数据由父组件提供 但是子组件内部决定不了自身结构与外观
子组件Todo代码如下:
<template>
<div>
<h1>todo</h1>
<ul>
<!--组件内部遍历数组-->
<li v-for="(item,index) in todos" :key="item.id">
<!--作用域插槽将数据回传给父组件-->
<slot :$row="item" :$index="index"></slot>
</li>
</ul>
</div>
</template>
<script setup lang="ts">
defineProps(['todos']);//接受父组件传递过来的数据
</script>
<style scoped>
</style>
父组件内部代码如下:
<template>
<div>
<h1>slot</h1>
<Todo :todos="todos">
<template v-slot="{$row,$index}">
<!--父组件决定子组件的结构与外观-->
<span :style="{color:$row.done?'green':'red'}">{{$row.title}}</span>
</template>
</Todo>
</div>
</template>
<script setup lang="ts">
import Todo from "./Todo.vue";
import { ref } from "vue";
//父组件内部数据
let todos = ref([
{ id: 1, title: "吃饭", done: true },
{ id: 2, title: "睡觉", done: false },
{ id: 3, title: "打豆豆", done: true },
]);
</script>
<style scoped>
</style>
下面几个例子将说明默认插槽 具名插槽 作用域插槽的不同:
//slot组件是Vue内部的组件标签
//子组件 Son
<template>
<h1>默认插槽包裹的内容</h1>
<slot>等待父组件填充子组件挖的坑</slot>
<h1>默认插槽包裹的内容</h1>
<h1>具名插槽包裹的内容</h1>
//带有name属性的slot组件即为具名插槽
<slot name="a">等待父组件填充子组件挖的坑</slot>
<h1>具名插槽包裹的内容</h1>
//作用域插槽就是可以传递数据的插槽 子组件可以将父组件通过props传递的数据通过作用域插槽回传给父组件 父组件可以根据回传的数据 决定子组件内部按照何种结构展示这些数据
//下面这段内容可能会被误会为向slot组件传递props属性 但是其实是作用域插槽回传数据的语法
<slot name="a">等待父组件填充子组件挖的坑</slot>
<h1>作用域插槽包裹的内容</h1>
//slot标签内
<slot name="a">等待父组件填充子组件挖的坑</slot>
<h1>作用域插槽包裹的内容</h1>
</template>
<script>
import {ref} from "vue"
const props = defineProps("[money]")
</script>
//父组件
<template>
<Son :money="money">
<h1>默认插槽的内容</h1>
//下面的内容将填充到具名插槽中 用来填充的内容必须用template包裹
<template v-slot:a> //表明要填充的是名为a的具名插槽
<div>具名插槽的内容</div>
</tempate>
</Son>
</tempalate>
<script>
import {ref} from "vue"
const money = ref("1000")
</script>