【props】
props是使用频率最高的一种通信方式,常用与 :父 <--> 子
- 若 父传子:属性值是非函数。
- 若 子传父:属性值是函数。
父组件:
<template>
<div class="father">
<h3>父组件,</h3>
<h4>我的车:{{ car }}</h4>
<h4>儿子给的玩具:{{ toy }}</h4>
<Child :car="car" :getToy="getToy"/>
</div>
</template>
<script setup lang="ts" name="Father">
import Child from './Child.vue'
import { ref } from "vue";
// 数据
const car = ref('奔驰')
const toy = ref()
// 方法
function getToy(value:string){
toy.value = value
}
</script>
子组件
<template>
<div class="child">
<h3>子组件</h3>
<h4>我的玩具:{{ toy }}</h4>
<h4>父给我的车:{{ car }}</h4>
<!-- <button @click="CliEven">把玩具给父亲</button> -->
<button @click="getToy(toy)">玩具给父亲</button>
</div>
</template>
<script setup lang="ts" name="Child">
import { ref } from "vue";
const toy = ref('奥特曼')
defineProps(['car','getToy'])
// const props = defineProps(["car", "sendToy"]);
// const CliEven = () => {
// props.sendToy(toy);
// };
</script>
【自定义事件】
自定义事件常用于:子 --> 父
示例:
// 子组件
const emit = defineEmits(["send-toy"]);// 声明事件
emit('send-toy', toy) // 触发事件
// 父组件
<Child @send-toy="getToy" /> // 给子组件Child绑定事件
- 声明自定义事件(defineEmits)
- 触发事件
- 父组件绑定事件
【mitt】
与消息订阅与发布(pubsub)功能类似,可以实现任意组件间通信
- 提供数据触发事件
emit(发布消息) - 接收数据绑定事件
on(订阅消息)
安装mitt
npm i mitt
新建文件:src\utils\emitter.ts
// 引入mitt
import mitt from "mitt";
// 创建emitter
const emitter = mitt()
/*
// 绑定事件
emitter.on('abc',(value)=>{
console.log('abc事件被触发',value)
})
emitter.on('xyz',(value)=>{
console.log('xyz事件被触发',value)
})
setInterval(() => {
// 触发事件
emitter.emit('abc',666)
emitter.emit('xyz',777)
}, 1000);
setTimeout(() => {
// 清理事件
emitter.all.clear()
}, 3000);
*/
// 创建并暴露mitt
export default emitter
接收数据的组件中:绑定事件、同时在销毁前解绑事件:
import emitter from "@/utils/emitter";
import { onUnmounted } from "vue";
// 绑定事件
emitter.on('send-toy',(value)=>{
console.log('send-toy事件被触发',value)
})
onUnmounted(()=>{
// 解绑事件
emitter.off('send-toy')
})
提供数据的组件,在合适的时候触发事件
import emitter from "@/utils/emitter";
function sendToy(){
// 触发事件
emitter.emit('send-toy',toy.value)
}
【v-model】
实现父 <--> 子之间相互通信(一般用于组件库底层)
前序知识 -- v-model的本质
<!-- 使用v-model指令 -->
<input type="text" v-model="userName">
<!-- v-model的本质是下面这行代码 -->
<input
type="text"
:value="userName"
@input="userName =(<HTMLInputElement>$event.target).value"
>
组件标签上的v-model的本质::moldeValue + update:modelValue事件。
<!-- 组件标签上使用v-model指令 -->
<CustomInput v-model="userName"/>
<!-- 组件标签上v-model的本质 -->
<CustomInput :modelValue="userName" @update:model-value="userName = $event"/>
CustomInput组件中:
<template>
<div class="box">
<!--将接收的value值赋给input元素的value属性,目的是:为了呈现数据 -->
<!--给input元素绑定原生input事件,触发input事件时,进而触发update:model-value事件-->
<input
type="text"
:value="modelValue"
@input="emit('update:model-value',$event.target.value)"
>
</div>
</template>
<script setup lang="ts" name="CustomInput">
// 接收props
defineProps(['modelValue'])
// 声明事件
const emit = defineEmits(['update:model-value'])
</script>
也可以更换value,例如改成abc
<!-- 也可以更换value,例如改成abc-->
<AtguiguInput v-model:abc="userName"/>
<!-- 上面代码的本质如下 -->
<AtguiguInput :abc="userName" @update:abc="userName = $event"/>
CustomInput组件中:
<template>
<div class="box">
<input
type="text"
:value="abc"
@input="emit('update:abc',$event.target.value)"
>
</div>
</template>
<script setup lang="ts" name="CustomInput">
// 接收props
defineProps(['abc'])
// 声明事件
const emit = defineEmits(['update:abc'])
</script>
如果value可以更换,那么就可以在组件标签上多次使用v-model
<CustomInput v-model:abc="userName" v-model:xyz="password"/>
- 概述:
$attrs用于实现当前组件的父组件,向当前组件的子组件通信(祖→孙)。 - 具体说明:
$attrs是一个对象,包含所有父组件传入的标签属性。
注意:$attrs会自动排除props中声明的属性(可以认为声明过的 props 被子组件自己“消费”了)
父组件:
<template>
<div class="father">
<h3>父组件</h3>
<Child :a="a" :b="b" :c="c" :d="d" v-bind="{x:100,y:200}" :updateA="updateA"/>
</div>
</template>
<script setup lang="ts" name="Father">
import Child from './Child.vue'
import { ref } from "vue";
let a = ref(1)
let b = ref(2)
let c = ref(3)
let d = ref(4)
function updateA(value){
a.value = value
}
</script>
子组件:
<template>
<div class="child">
<h3>子组件</h3>
<GrandChild v-bind="$attrs"/>
</div>
</template>
<script setup lang="ts" name="Child">
import GrandChild from './GrandChild.vue'
</script>
孙组件:
<template>
<div class="grand-child">
<h3>孙组件</h3>
<h4>a:{{ a }}</h4>
<h4>b:{{ b }}</h4>
<h4>c:{{ c }}</h4>
<h4>d:{{ d }}</h4>
<h4>x:{{ x }}</h4>
<h4>y:{{ y }}</h4>
<button @click="updateA(666)">点我更新A</button>
</div>
</template>
<script setup lang="ts" name="GrandChild">
defineProps(['a','b','c','d','x','y','updateA'])
</script>
【$attrs 】
$attrs用于实现当前组件的父组件,向当前组件的子组件通信(祖→孙)。
具体说明:$attrs是一个对象,包含所有父组件传入的标签属性。
注意:$attrs会自动排除props中声明的属性(可以认为声明过的 props 被子组件自己“消费”了)
父组件:
<template>
<div class="father">
<h3>父组件</h3>
<Child :a="a" :b="b" :c="c" :d="d" v-bind="{x:100,y:200}" :updateA="updateA"/>
</div>
</template>
<script setup lang="ts" name="Father">
import Child from './Child.vue'
import { ref } from "vue";
let a = ref(1)
let b = ref(2)
let c = ref(3)
let d = ref(4)
function updateA(value){
a.value = value
}
</script>
子组件:
<template>
<div class="child">
<h3>子组件</h3>
<GrandChild v-bind="$attrs"/>
</div>
</template>
<script setup lang="ts" name="Child">
import GrandChild from './GrandChild.vue'
</script>
孙组件:
<template>
<div class="grand-child">
<h3>孙组件</h3>
<h4>a:{{ a }}</h4>
<h4>b:{{ b }}</h4>
<h4>c:{{ c }}</h4>
<h4>d:{{ d }}</h4>
<h4>x:{{ x }}</h4>
<h4>y:{{ y }}</h4>
<button @click="updateA(666)">点我更新A</button>
</div>
</template>
<script setup lang="ts" name="GrandChild">
defineProps(['a','b','c','d','x','y','updateA'])
</script>
【$refs、$parent】
概述:
$refs用于 :父→子。$parent用于:子→父。
原理如下:
$refs:值为对象,包含所有被ref属性标识的DOM元素或组件实例。
$parent:值为对象,当前组件的父组件实例对象。
$refs是所有的ref
都需要使用defineExpose({ }) 把数据交给外部
示例代码如下:
父组件:
<template>
<div class="father">
<h3>父组件</h3>
<h4>房产:{{ house }}套</h4>
<button @click="updateToy">修个儿子的玩具</button>
<button @click="getAllChildren($refs)">给所有儿子书加三本</button>
<Child1 ref="c1" />
</div>
</template>
<script setup lang="ts" name="Father">
import Child1 from "./Child1.vue";
import { ref } from "vue";
let c1 = ref();
let house = ref(4);
function updateToy() {
c1.value.toy = "小猪佩奇";
}
function getAllChildren(refs: { [key: string]: any }) {
for (const key in refs) {
refs[key].book += 3;
}
}
defineExpose({ house });
子组件:
<template>
<div class="child1">
<h3>子组件1</h3>
<h4>玩具:{{ toy }}</h4>
<h4>书籍:{{ book }}本</h4>
<button @click="minuseHouse($parent)">干掉父亲的一套房产</button>
</div>
</template>
<script setup lang="ts" name="Child1">
import { ref } from "vue";
let toy = ref("奥特曼");
let book = ref(4);
function minuseHouse(parent: any) {
parent.house -= 1;
}
// 把数据交给外部
defineExpose({ toy, book });
</script>
【provide、inject】
概念:实现祖<->孙直接通信
具体使用:
- 在祖先组件中通过
provide配置向后代组件提供数据 - 在后代组件中通过
inject配置来声明接收数据
具体编码:
父组件中使用provide提供数据,这里传递的值不能.value不然没有响应式
<template>
<div class="father">
<h3>父组件</h3>
<h4>我的资产{{ money }}万</h4>
<h4>我的车:{{ car.brand }}--价格:{{ car.price }}</h4>
<Child />
</div>
</template>
<script setup lang="ts" name="Father">
import Child from "./Child.vue";
import { ref, reactive, provide } from "vue";
let money = ref<number>(100);
let car = reactive({
brand: "BMW",
price: 100,
});
// 用于更新money的方法(孙-->祖通信)
function spendMoney(val: number) {
money.value -= val;
}
// 提供数据
provide("moneyContext", { money, spendMoney });
provide("car", car);
</script>
注意:子组件中不用编写任何东西,是不受到任何打扰的
孙组件中使用inject配置项接受数据
<template>
<div class="grand-child">
<h3>我是孙组件</h3>
<h4>金币:{{ money }}W</h4>
<h4>车:{{ car.brand }}--{{ car.price }}</h4>
<button @click="spendMoney(6)">暴老头金币</button>
</div>
</template>
<script setup lang="ts" name="GrandChild">
import { inject } from "vue";
let { money, spendMoney } = inject("moneyContext", {
money: 0,
spendMoney: (x: number) => {},
});
let car = inject("car", { brand: "未知", price: 0 });
</script>
孙 --> 祖 通信也是使用函数调用
【slot】
默认插槽
父组件中:
<Category title="今日热门游戏">
<ul>
<li v-for="g in games" :key="g.id">{{ g.name }}</li>
</ul>
</Category>
子组件中:
<template>
<div class="item">
<h3>{{ title }}</h3>
<!-- 默认插槽 -->
<slot></slot>
</div>
</template>
具名插槽
父组件中:
<Category title="今日热门游戏">
<template v-slot:s1>
<ul>
<li v-for="g in games" :key="g.id">{{ g.name }}</li>
</ul>
</template>
<template #s2>
<a href="">更多</a>
</template>
</Category>
子组件中:
<template>
<div class="item">
<h3>{{ title }}</h3>
<slot name="s1"></slot>
<slot name="s2"></slot>
</div>
</template>
作用域插槽
数据在组件的自身(子组件),但根据数据生成的结构需要组件的使用者(父组件)来决定。
示例代码如下:
父组件中:
<Game v-slot="params">
<!-- <Game v-slot:default="params"> -->
<!-- <Game #default="params"> -->
<ul>
<li v-for="g in params.games" :key="g.id">{{ g.name }}</li>
</ul>
</Game>
<Game>
<template v-slot="params">
<ol>
<li v-for="item in params.youxi" :key="item.id">
{{ item.name }}
</li>
</ol>
</template>
</Game>
子组件中:
<template>
<div class="category">
<h2>今日游戏榜单</h2>
<slot :games="games" a="哈哈"></slot>
</div>
</template>
<script setup lang="ts" name="Category">
import {reactive} from 'vue'
let games = reactive([
{id:'asgdytsa01',name:'英雄联盟'},
{id:'asgdytsa02',name:'王者荣耀'},
{id:'asgdytsa03',name:'红色警戒'},
{id:'asgdytsa04',name:'斗罗大陆'}
])
</script>
v-slot="params"获取的子组件slot的所有值
- 作用域插槽也可以有名字
v-slot:name="params" - 没有名字可以不写或者
v-slot:default="params"、#default="params"语法糖简写形式(组件库中经常用到)
813

被折叠的 条评论
为什么被折叠?



