Vue组件通信

组件通信

父子双传

props

父传子

image-20240825201917435-ppsw.png

子传父

image-20240825203836739-eekr.png

v-model(双向绑定)

表单

1
2
3
4
5
//用在html标签
<input type="text" v-model="username">

//用在组件标签上
<组件 v-model="username"/>

image-20240826134133823-jtfn.png

image-20240826134643288-wved.png

父传子

$refs

改变子的玩具

image-20240826163102996-vnxq.png

让所有子的书变多

image-20240826161006792-cmyw.png

默认插槽

image-20240826214619312-wydc.png

image-20240826214724976-nytt.png

具名插槽

image-20240826221750773-jrvs.png

子传父

自定义

父组件

1
<Child @send-toy="toy = $event"/>

子组件

1
this.$emit('send-toy', 具体数据)

image-20240825212202117-gpof.png

$parent

减少父的房产

image-20240826162719642-svvx.png

作用域插槽

params 作为对象

image-20240827151102500-ymag.png

image-20240827151700297-slyx.png

祖传孙

$attrs

image-20240826144203197-vibc.png

provide(配 inject)

image-20240826172233626-cazp.png

孙传组

inject(配 provid)

image-20240826172226760-ueqn.png

兄弟传

mitt

安装

1
npm i mitt

/utils/emitter

1
2
3
4
5
6
7
8
//引入mitt
import mitt from 'mitt'

// 调用mitt得到emitter,emitter能:绑定事件、触发事件
const emitter = mitt()

// 暴露emitter
export default emitter
1
2
3
4
5
6
7
8
//绑定事件
emitter.on('text',()=>{})
//触发事件
emmiter.emit('text')
//解绑事件
emmiter.off('text')
//全部解绑
emmiter.all.clear()

image-20240826131941301-xtro.png

任意传

pinia

搭建

1
npm install pinia

main.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
import { createApp } from 'vue'
import App from './App.vue'

/* 引入createPinia,用于创建pinia */
import { createPinia } from 'pinia'

/* 创建pinia */
const pinia = createPinia()
const app = createApp(App)

/* 使用插件 */{}
app.use(pinia)
app.mount('#app')

/stores/first.ts

1
2
3
4
5
6
7
8
9
import {defineStore} from "pinia";

import {ref} from "vue"

export default defineStore('first',()=>{//创建自己的仓库
const name = ref('pinia');

return {name};
})

App.vue

1
2
3
4
5
6
7
8
<script>
import useFristStore from "./stores/first"
const store = useFirstStore();//自己的仓库
console.log(store.name);
</script>
<template>

</template>