关于前端:Vue3-10种组件通信方式

4次阅读

共计 15630 个字符,预计需要花费 40 分钟才能阅读完成。

本文简介

点赞 + 关注 + 珍藏 = 学会了

本文解说 Vue 3.2 组件多种通信形式的根底用法,并且应用了 单文件组件 <script setup>

家喻户晓,Vue.js 中一个很重要的知识点是组件通信,不论是业务类的开发还是组件库开发,都有各自的通信办法。

本文适宜:

  1. Vue 3 根底的读者。
  2. 打算开发组件库的读者。

本文会波及的知识点:

  1. Props
  2. emits
  3. expose / ref
  4. Non-Props
  5. v-model
  6. 插槽 slot
  7. provide / inject
  8. 总线 bus
  9. getCurrentInstance
  10. Vuex
  11. Pinia
  12. mitt.js

我会将下面列举的知识点都写一个简略的 demo。本文的目标是让大家晓得有这些办法能够用,所以并不会深挖每个知识点。

倡议读者跟着本文敲一遍代码,而后依据本文给出的链接去深挖各个知识点。

珍藏 (学到) 是本人的!

Props

父组件传值给子组件(简称:父传子)

Props 文档

父组件

// Parent.vue

<template>
  <!-- 应用子组件 -->
  <Child :msg="message" />
</template>

<script setup>
import Child from './components/Child.vue' // 引入子组件

let message = '雷猴'
</script>

子组件

// Child.vue

<template>
  <div>
    {{msg}}
  </div>
</template>

<script setup>

const props = defineProps({
  msg: {
    type: String,
    default: ''
  }
})

console.log(props.msg) // 在 js 里须要应用 props.xxx 的形式应用。在 html 中应用不须要 props

</script>

<script setup> 中必须应用 defineProps API 来申明 props,它具备残缺的推断并且在 <script setup> 中是间接可用的。

更多细节请看 文档。

<script setup> 中,defineProps 不须要另外引入。

props 其实还能做很多事件,比方:设置默认值 default,类型验证 type,要求必传 required,自定义验证函数 validator 等等。

大家能够去官网看看,这是 必须把握 的知识点!

props 文档

emits

子组件告诉父组件触发一个事件,并且能够传值给父组件。(简称:子传父)

emits 文档

父组件

// Parent.vue

<template>
  <div> 父组件:{{message}}</div>
  <!-- 自定义 changeMsg 事件 -->
  <Child @changeMsg="changeMessage" />
</template>

<script setup>
import {ref} from 'vue'
import Child from './components/Child.vue'

let message = ref('雷猴')

// 更改 message 的值,data 是从子组件传过来的
function changeMessage(data) {message.value = data}
</script>

子组件

// Child.vue

<template>
  <div>
    子组件:<button @click="handleClick"> 子组件的按钮 </button>
  </div>
</template>

<script setup>

// 注册一个自定义事件名,向上传递时通知父组件要触发的事件。const emit = defineEmits(['changeMsg'])

function handleClick() {
  // 参数 1:事件名
  // 参数 2:传给父组件的值
  emit('changeMsg', '鲨鱼辣椒')
}

</script>

props 一样,在 <script setup> 中必须应用 defineEmits API 来申明 emits,它具备残缺的推断并且在 <script setup> 中是间接可用的。更多细节请看 文档。

<script setup> 中,defineEmits 不须要另外引入。

expose / ref

子组件能够通过 expose 裸露本身的办法和数据。

父组件通过 ref 获取到子组件并调用其办法或拜访数据。

expose 文档

用例子谈话

父组件

// Parent.vue

<template>
  <div> 父组件:拿到子组件的 message 数据:{{msg}}</div>
  <button @click="callChildFn"> 调用子组件的办法 </button>

  <hr>

  <Child ref="com" />
</template>

<script setup>
import {ref, onMounted} from 'vue'
import Child from './components/Child.vue'

const com = ref(null) // 通过 模板 ref 绑定子组件

const msg = ref('')

onMounted(() => {
  // 在加载实现后,将子组件的 message 赋值给 msg
  msg.value = com.value.message
})

function callChildFn() {
  // 调用子组件的 changeMessage 办法
  com.value.changeMessage('蒜头王八')

  // 从新将 子组件的 message 赋值给 msg
  msg.value = com.value.message
}
</script>

子组件

// Child.vue

<template>
  <div> 子组件:{{message}}</div>
</template>

<script setup>
import {ref} from 'vue'

const message = ref('蟑螂恶霸')

function changeMessage(data) {message.value = data}

应用 defineExpose 向外裸露指定的数据和办法
defineExpose({
  message,
  changeMessage
})

</script>

<script setup> 中,defineExpose 不须要另外引入。

expose 文档

defineExpose 文档

Non-Props

所谓的 Non-Props 就是 非 Prop 的 Attribute。

意思是在子组件中,没应用 propemits 定义的 attribute,能够通过 $attrs 来拜访。

常见的有 classstyleid

非 Prop 的 Attribute 文档

还是举个例子会直观点

单个根元素的状况

父组件

// Parent.vue

<template>
  <Child msg="雷猴 世界!" name="鲨鱼辣椒" />
</template>

<script setup>
import {ref} from 'vue'
import Child from './components/Child.vue'
</script>

子组件

// Child.vue

<template>
  <div> 子组件:关上控制台看看 </div>
</template>

关上控制台能够看到,属性被挂到 HTML 元素上了。

多个元素的状况

但在 Vue3 中,组件曾经没规定只能有一个根元素了。如果子组件是多个元素时,下面的例子就不失效了。

// Child.vue

<template>
  <div> 子组件:关上控制台看看 </div>
  <div> 子组件:关上控制台看看 </div>
</template>

此时能够应用 $attrs 的形式进行绑定。

// Child.vue

<template>
  <div :message="$attrs.msg"> 只绑定指定值 </div>
  <div v-bind="$attrs"> 全绑定 </div>
</template>

v-model

v-modelVue 的一个语法糖。在 Vue3 中的玩法就更多 (晕) 了。

单值的状况

组件上的 v-model 应用 modelValue 作为 prop 和 update:modelValue 作为事件。

v-model 参数文档

父组件

// Parent.vue

<template>
  <Child v-model="message" />
</template>

<script setup>
import {ref} from 'vue'
import Child from './components/Child.vue'

const message = ref('雷猴')
</script>

子组件

// Child.vue

<template>
  <div @click="handleClick">{{modelValue}}</div>
</template>

<script setup>
import {ref} from 'vue'

// 接管
const props = defineProps(['modelValue' // 接管父组件应用 v-model 传进来的值,必须用 modelValue 这个名字来接管])

const emit = defineEmits(['update:modelValue']) // 必须用 update:modelValue 这个名字来告诉父组件批改值

function handleClick() {
  // 参数 1:告诉父组件批改值的办法名
  // 参数 2:要批改的值
  emit('update:modelValue', '喷射河马')
}

</script>

你也能够这样写,更加简略

子组件

// Child.vue

<template>
  <div @click="$emit('update:modelValue',' 喷射河马 ')">{{modelValue}}</div>
</template>

<script setup>
import {ref} from 'vue'

// 接管
const props = defineProps(['modelValue' // 接管父组件应用 v-model 传进来的值,必须用 modelValue 这个名字来接管])

</script>

多个 v-model 绑定

多个 v-model 绑定 文档

父组件

// Parent.vue

<template>
  <Child v-model:msg1="message1" v-model:msg2="message2" />
</template>

<script setup>
import {ref} from 'vue'
import Child from './components/Child.vue'

const message1 = ref('雷猴')

const message2 = ref('蟑螂恶霸')
</script>

子组件

// Child.vue

<template>
  <div><button @click="changeMsg1"> 批改 msg1</button> {{msg1}}</div>

  <div><button @click="changeMsg2"> 批改 msg2</button> {{msg2}}</div>
</template>

<script setup>
import {ref} from 'vue'

// 接管
const props = defineProps({
  msg1: String,
  msg2: String
})

const emit = defineEmits(['update:msg1', 'update:msg2'])

function changeMsg1() {emit('update:msg1', '鲨鱼辣椒')
}

function changeMsg2() {emit('update:msg2', '蝎子莱莱')
}

</script>

v-model 修饰符

v-model 还能通过 . 的形式传入润饰。

v-model 修饰符 文档

父组件

// Parent.vue

<template>
  <Child v-model.uppercase="message" />
</template>

<script setup>
import {ref} from 'vue'
import Child from './components/Child.vue'

const message = ref('hello')
</script>

子组件

// Child.vue

<template>
  <div>{{modelValue}}</div>
</template>

<script setup>
import {ref, onMounted} from 'vue'

const props = defineProps([
  'modelValue',
  'modelModifiers'
])

const emit = defineEmits(['update:modelValue'])

onMounted(() => {// 判断有没有 uppercase 修饰符,有的话就执行 toUpperCase() 办法
  if (props.modelModifiers.uppercase) {emit('update:modelValue', props.modelValue.toUpperCase())
  }
})

</script>

插槽 slot

插槽能够了解为传一段 HTML 片段给子组件。子组件将 <slot> 元素作为承载散发内容的进口。

插槽 文档

本文打算讲讲日常用得比拟多的 3 种插槽:默认插槽、具名插槽、作用域插槽。

默认插槽

插槽的根底用法非常简单,只需在 子组件 中应用 <slot> 标签,就会将父组件传进来的 HTML 内容渲染进去。

默认插槽 文档

父组件

// Parent.vue

<template>
  <Child>
    <div> 雷猴啊 </div>
  </Child>
</template>

子组件

// Child.vue

<template>
  <div>
    <slot></slot>
  </div>
</template>

具名插槽

具名插槽 就是在 默认插槽 的根底上进行分类,能够了解为对号入座。

具名插槽 文档

父组件

// Parent.vue

<template>
  <Child>
    <template v-slot:monkey>
      <div> 雷猴啊 </div>
    </template>

    <button> 鲨鱼辣椒 </button>
  </Child>
</template>

子组件

// Child.vue

<template>
  <div>
    <!-- 默认插槽 -->
    <slot></slot>
    <!-- 具名插槽 -->
    <slot name="monkey"></slot>
  </div>
</template>

父组件须要应用 <template> 标签,并在标签上应用 v-solt: + 名称

子组件须要在 <slot> 标签里用 name= 名称 对应接管。

这就是 对号入座

最初须要留神的是,插槽内容的排版程序,是 以子组件里的排版为准

下面这个例子就是这样,你能够仔细观察子组件传入程序和子组件的排版程序。

作用域插槽

如果你用过 Element-Plus 这类 UI 框架 的 Table,应该就能很好的了解什么叫作用域插槽。

作用域插槽 文档

父组件

// Parent.vue

<template>
  <!-- v-slot="{scope}" 获取子组件传上来的数据 -->
  <!-- :list="list" 把 list 传给子组件 -->
  <Child v-slot="{scope}" :list="list">
    <div>
      <div> 名字:{{scope.name}}</div>
      <div> 职业:{{scope.occupation}}</div>
      <hr>
    </div>
  </Child>
</template>

<script setup>
import {ref} from 'vue'
import Child from './components/Child.vue'

const list = ref([{ name: '雷猴', occupation: '打雷'},
  {name: '鲨鱼辣椒', occupation: '游泳'},
  {name: '蟑螂恶霸', occupation: '扫地'},
])
</script>

子组件

// Child.vue

<template>
  <div>
    <!-- 用 :scope="item" 返回每一项 -->
    <slot v-for="item in list" :scope="item" />
  </div>
</template>

<script setup>
const props = defineProps({
  list: {
    type: Array,
    default: () => []
  }
})
</script>

我没写款式,所以用 hr 元素让视觉上看上去比拟清晰 我就是懒

provide / inject

遇到多层传值时,应用 propsemit 的形式会显得比拟蠢笨。这时就能够用 provideinject 了。

provide 是在父组件里应用的,能够往下传值。

inject 是在子 (后辈) 组件里应用的,能够网上取值。

无论组件层次结构有多深,父组件都能够作为其所有子组件的依赖提供者。

provide / inject 文档

父组件

// Parent.vue

<template>
  <Child></Child>
</template>

<script setup>
import {ref, provide, readonly} from 'vue'
import Child from './components/Child.vue'

const name = ref('猛虎下山')
const msg = ref('雷猴')

// 应用 readonly 能够让子组件无奈间接批改,须要调用 provide 往下传的办法来批改
provide('name', readonly(name))

provide('msg', msg)

provide('changeName', (value) => {name.value = value})
</script>

子组件

// Child.vue

<template>
  <div>
    <div>msg: {{msg}}</div>
    <div>name: {{name}}</div>
    <button @click="handleClick"> 批改 </button>
  </div>
</template>

<script setup>
import {inject} from 'vue'

const name = inject('name', 'hello') // 看看有没有值,没值的话就实用默认值(这里默认值是 hello)const msg = inject('msg')
const changeName = inject('changeName')

function handleClick() {
  // 这样写不适合,因为 vue 里举荐应用单向数据流,当父级应用 readonly 后,这行代码是不会失效的。没应用之前才会失效。// name.value = '雷猴'

  // 正确的形式
  changeName('虎躯一震')

  // 因为 msg 没被 readonly 过,所以能够间接批改值
  msg.value = '世界'
}
</script>

provide 能够配合 readonly 一起应用,详情能够看下面例子和正文。

provideinject 其实次要是用在深层关系中传值,下面的例子只有父子 2 层,只是为了举例说明 我懒

总线 bus

Vue2 有总线传值的办法,咱们在 Vue3 中也能够本人模仿。

这个形式其实有点像 Vuex 或者 Pinia 那样,弄一个独立的工具进去专门控制数据。

但和 VuexPinia 相比,咱们本人写的这个办法并没有很好的数据跟踪之类的个性。

原理

咱们创立一个 Bus.js 文件,用来控制数据和注册事件的。

Bus.js 里有一个 Bus

  • eventList 是必须项,用来寄存事件列表的。
  • constructor 里除了 eventList 外,其余都是自定义数据,公共数据就是存在这里的。
  • $on 办法用来注册事件。
  • $emit 办法能够调用 $on 里的事件。
  • $off 办法能够登记 eventList 里的事件。

而后须要用到总线的组件,都导入 Bus.js,就能够独特操作一份数据了。

Bus.js

import {ref} from 'vue'

class Bus {constructor() {
    // 收集订阅信息, 调度核心
    this.eventList = {}, // 事件列表,这项是必须的
    // 上面的都是自定义值
    this.msg = ref('这是一条总线的信息')
  }

  // 订阅
  $on(name, fn) {this.eventList[name] = this.eventList[name] || []
    this.eventList[name].push(fn)
  }

  // 公布
  $emit(name, data) {if (this.eventList[name]) {this.eventList[name].forEach((fn) => {fn(data)
      });
    }
  }

  // 勾销订阅
  $off(name) {if (this.eventList[name]) {delete this.eventList[name]
    }
  }
}

export default new Bus()

父组件

// Parent.vue

<template>
  <div>
    父组件: 
    <span style="margin-right: 30px;">message: {{message}}</span>
    <span>msg: {{msg}}</span>
  </div>
  <Child></Child>
</template>

<script setup>
import {ref} from 'vue'
import Bus from './Bus.js'
import Child from './components/Child.vue'

const msg = ref(Bus.msg)

const message = ref('hello')

// 用监听的写法
Bus.$on('changeMsg', data => {message.value = data})

</script>

子组件

// Child.vue

<template>
  <div>
    子组件:<button @click="handleBusEmit"> 触发 Bus.$emit</button>
    <button @click="changeBusMsg"> 批改总线里的 msg</button>
  </div>
</template>

<script setup>
import Bus from '../Bus.js'

function handleBusEmit() {Bus.$emit('changeMsg', '雷猴啊')
}

function changeBusMsg() {// console.log(Bus.msg)
  Bus.msg.value = '在子组件里批改了总线的值'
}
</script>

这个办法其实还挺好用的,但光看可能有点懵,请大家务必亲手敲一下代码实际一下。

getCurrentInstance

getcurrentinstancevue 提供的一个办法,反对拜访外部组件实例。

getCurrentInstance 只裸露给高阶应用场景,典型的比方在库中。强烈拥护在利用的代码中应用 getCurrentInstance。请 不要 把它当作在组合式 API 中获取 this 的代替计划来应用。

说白了,这个办法 适宜在开发组件库的状况下应用,不适宜日常业务开发中应用。

getCurrentInstance 只能 在 setup 或生命周期钩子中调用。

getcurrentinstance 文档

<script setup> 中,我模仿了相似 $parent$children 的形式。

父组件

// Parent.vue

<template>
  <div> 父组件 message 的值: {{message}}</div>
  <button @click="handleClick"> 获取子组件 </button>
  <Child></Child>
  <Child></Child>
</template>

<script setup>
import {ref, getCurrentInstance, onMounted} from 'vue'
import Child from './components/Child.vue'

const message = ref('雷猴啊')

let instance = null

onMounted(() => {instance = getCurrentInstance()
})

// 子组件列表
let childrenList = []

// 注册组件
function registrationCom(com) {childrenList.push(com)
}

function handleClick() {if (childrenList.length > 0) {
    childrenList.forEach(item => {console.log('组件实例:', item)
      console.log('组件名(name):', item.type.name)
      console.log('组件输入框的值:', item.devtoolsRawSetupState.inputValue)
      console.log('---------------------------------------')
    })
  }
}

</script>

子组件

// Child.vue

<template>
  <div>
    <div>----------------------------</div>
    子组件:<button @click="handleClick"> 获取父组件的值 </button>
    <br>
    <input type="text" v-model="inputValue">
  </div>
</template>

<script>
export default {name: 'ccccc'}
</script>

<script setup>
import {getCurrentInstance, onMounted, nextTick, ref} from 'vue'

const inputValue = ref('')

let instance = null

onMounted(() => {instance = getCurrentInstance()
  nextTick(() => {instance.parent.devtoolsRawSetupState.registrationCom(instance)
  })

})

function handleClick() {
  let msg = instance.parent.devtoolsRawSetupState.message
  msg.value = '哈哈哈哈哈哈'
}

</script>

能够将代码复制到你的我的项目中运行试试看,最好还是敲一遍咯。

Vuex

Vuex 次要解决 跨组件通信 的问题。

Vue3 中,须要应用 Vuex v4.x 版本。

装置

npm 或者 Yarn 装置到我的项目中。

npm install vuex@next --save

# 或

yarn add vuex@next --save

应用

装置胜利后,在 src 目录下创立 store 目录,再在 store 下创立 index.js 文件。

// store/index.js

import {createStore} from 'vuex'

export default createStore({state: {},
  getters: { },
  mutations: { },
  actions: { },
  modules: {}})

store/index.js 下输出以上内容。

  • state:数据仓库,用来存数据的。
  • getters:获取数据的,有点像 computed 的用法(集体感觉)。
  • mutations: 更改 state 数据的办法都要写在 mutations 里。
  • actions:异步异步异步,异步的办法都写在这里,但最初还是须要通过 mutations 来批改 state 的数据。
  • modules:分包。如果我的项目比拟大,能够将业务拆散成独立模块,而后分文件治理和寄存。

而后在 src/main.js 中引入

import {createApp} from 'vue'
import App from './App.vue'
import store from './store'

const app = createApp(App)

app
  .use(store)
  .mount('#app')

State

store/index.js

// store/index.js

import {createStore} from 'vuex'

export default createStore({
  state: {msg: '雷猴'}
})

组件

// xxx.vue

<script setup>
import {useStore} from 'vuex'

const store = useStore()

console.log(store.state.msg) // 雷猴
</script>

Getter

我感觉 Getter 办法和 computed 是有点像的。

比方咱们须要过滤一下数据,或者返回时组装一下数据,都能够用 Getter 办法。

store/index.js

// store/index.js

import {createStore} from 'vuex'

export default createStore({
  state: {msg: '雷猴'},
  getters: {getMsg(state) {return state.msg + '世界!'}
  }
})

组件

// xxx.vue

<script setup>
import {useStore} from 'vuex'

const store = useStore()

console.log(store.getters.getMsg) // 雷猴 世界!</script>

Mutation

Mutation 是批改 State 数据的惟一办法,这样 Vuex 才能够跟踪数据流向。

在组件中通过 commit 调用即可。

store/index.js

// store/index.js

import {createStore} from 'vuex'

export default createStore({
  state: {msg: '雷猴'},
  mutations: {changeMsg(state, data) {state.msg = data}
  }
})

组件

// xxx.vue

<script setup>
import {useStore} from 'vuex'

const store = useStore()

store.commit('changeMsg', '蒜头王八')

console.log(store.state.msg) // 蒜头王八
</script>

Action

我习惯将异步的货色放在 Action 办法里写,而后在组件应用 dispatch 办法调用。

store/index.js

// store/index.js

import {createStore} from 'vuex'

export default createStore({
  state: {msg: '雷猴'},
  mutations: {changeMsg(state, data) {state.msg = data}
  },
  actions: {fetchMsg(context) {
      // 模仿 ajax 申请
      setTimeout(() => {context.commit('changeMsg', '鲨鱼辣椒')
      }, 1000)
    }
  }
})

组件

// xxx.vue

<script setup>
import {useStore} from 'vuex'

const store = useStore()

store.dispatch('fetchMsg')
</script>

Module

Module 就是传说中的分包了。这须要你将不同模块的数据拆分成一个个 js 文件。

我举个例子,目录如下

store
|- index.js
|- modules/
  |- user.js
  |- goods.js
  • index.js 对外的进口(主文件)
  • modules/user.js 用户相干模块
  • modules/goods.js 商品模块

index.js

import {createStore} from 'vuex'
import user from './modules/user'
import goods from './modules/goods'

export default createStore({state: {},
  getters: {},
  mutations: {},
  actions: {},
  modules: {
    user,
    goods
  }
})

user.js

const user = {state: {},
  getters: { },
  mutations: { },
  actions: {}}

export default user

goods.js

const goods = {state: {},
  getters: { },
  mutations: { },
  actions: {}}

export default goods

而后在各个模块里放入相应的数据和办法就行。

在组建中调用办法和拜访数据,都和之前的用法差不多的。

以上就是 Vuex 的根底用法。除此之外,Vuex 还有各种语法糖,大家能够自行查阅 官网文档

Pinia

Pinia 是最近比拟炽热的一个工具,也是用来解决 跨组件通信 的,极大可能成为 Vuex 5

Pinia 文档

从我应用 Pinia 一阵后的角度来看,PiniaVuex 相比有以下长处:

  • 调用时代码跟简洁了。
  • TS 更敌对。
  • 合并了 VuexMutationAction。人造的反对异步了。
  • 人造分包。

除此之外,Pinia 官网还说它实用于 Vue2Vue3。但我没试过在 Vue2 中应用 我懒得试

Pinia 简化了状态治理模块,只用这 3 个货色就能应答日常大多工作。

  • state:存储数据的仓库
  • getters:获取和过滤数据(跟 computed 有点像)
  • actions:寄存“批改 state”的办法

我举个简略的例子

装置

npm install pinia

# 或

yarn add pinia

注册

src 目录下创立 store 目录,再在 store 里创立 index.jsuser.js

目录构造如下

store
|- index.js
|- user.js

index.js

import {createPinia} from 'pinia'

const store = createPinia()

export default store

user.js

常见的写法有 2 种,选其中一种就行。

import {defineStore} from 'pinia'

// 写法 1
export const useUserStore = defineStore({
  id: 'user', // id 必填,且须要惟一
  state: () => {
    return {name: '雷猴'}
  },
  getters: {fullName: (state) => {return '我叫' + state.name}
  },
  actions: {updateName(name) {this.name = name}
  }
})


// 写法 2
export const useUserStore = defineStore('user',{state: () => {
    return {name: '雷猴'}
  },
  getters: {fullName: (state) => {return '我叫' + state.name}
  },
  actions: {updateName(name) {this.name = name}
  }
})

而后在 src/main.js 中引入 store/index.js

src/main.js

import {createApp} from 'vue'
import App from './App.vue'
import store from './store'

const app = createApp(App)

app
  .use(store)
  .mount('#app')

在组件中应用

组件

// xxx.vue

<template>
  <div>
    <div>name: {{name}}</div>
    <div> 全名:{{fullName}}</div>
    <button @click="handleClick"> 批改 </button>
  </div>
</template>

<script setup>
import {computed} from 'vue'
import {storeToRefs} from 'pinia'
import {useUserStore} from '@/store/user'

const userStore = useUserStore()

// const name = computed(() => userStore.name)

// 倡议
const {name, fullName} = storeToRefs(userStore)


function handleClick() {
  // 不倡议这样改
  // name.value = '蝎子莱莱'

  // 举荐的写法!!!userStore.updateName('李四')
}
</script>

啰嗦两句

其实 Pinia 的用法和 Vuex 是挺像的,默认就是分包的逻辑,在这方面我反对 菠萝(Pinia)

Pinia 还提供了多种语法糖,强烈建议浏览一下 官网文档。

mitt.js

咱们后面用到的 总线 Bus 办法,其实和 mitt.js 有点像,但 mitt.js 提供了更多的办法。

比方:

  • on:增加事件
  • emit:执行事件
  • off:移除事件
  • clear:革除所有事件

mitt.js 不是专门给 Vue 服务的,但 Vue 能够利用 mitt.js 做跨组件通信。

github 地址

npm 地址

装置

npm i mitt 

应用

我模仿一下 总线 Bus 的形式。

我在同级目录创立 3 个文件用作模仿。

Parent.vue
Child.vue
Bus.js

Bus.js

// Bus.js

import mitt from 'mitt'
export default mitt()

Parent.vue

// Parent.vue

<template>
  <div>
    Mitt
    <Child />
  </div>
</template>

<script setup>
import Child from './Child.vue'
import Bus from './Bus.js'

Bus.on('sayHello', () => console.log('雷猴啊'))
</script>

Child.vue

// Child.vue

<template>
  <div>
    Child:<button @click="handleClick"> 打声招呼 </button>
  </div>
</template>

<script setup>
import Bus from './Bus.js'

function handleClick() {Bus.emit('sayHello')
}
</script>

此时,点击 Child.vue 上的按钮,在控制台就会执行在 Parent.vue 里定义的办法。

mitt.js 的用法其实很简略,倡议跟着 官网示例 敲一下代码,几分钟就上手了。

举荐浏览

👍《console.log 也能插图》

👍《Vite 搭建 Vue2 我的项目(Vue2 + vue-router + vuex)》

如果本文对你有帮忙,也心愿你能够 点赞 关注 珍藏 ~ 这对我很有用 ~

正文完
 0