찾다
웹 프론트엔드View.jsVue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법

Vue구성요소 간 통신 방법은 무엇인가요? 다음 글에서는 10가지 이상의 Vue3 컴포넌트 통신 방법을 공유하겠습니다. 여러분에게 도움이 되기를 바랍니다.

Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법

이 글에서는 Vue 3.2 컴포넌트의 다양한 통신 방식의 기본적인 사용법을 설명하고, 단일 파일 컴포넌트을 사용합니다. Vue 3.2 组件多种通讯方式的基础用法,并且使用了  单文件组件 <script setup></script>

众所周知,Vue.js 中一个很重要的知识点是组件通信,不管是业务类的开发还是组件库开发,都有各自的通讯方法。【相关推荐:vuejs视频教程

本文适合:

  • Vue 3 基础的读者。

  • 打算开发组件库的读者。

本文会涉及的知识点:

  • Props

  • emits

  • expose / ref

  • Non-Props

  • v-model

  • 插槽 slot

  • provide / inject

  • 总线 bus

  • getCurrentInstance

  • Vuex

  • Pinia

  • mitt.js

我会将上面罗列的知识点都写一个简单的 demo。本文的目的是让大家知道有这些方法可以用,所以并不会深挖每个知识点。

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

收藏(学到)是自己的!

Props

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

Props 文档

https://v3.cn.vuejs.org/guide/component-props.html

父组件

// Parent.vue

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

<script setup>
import Child from &#39;./components/Child.vue&#39; // 引入子组件

let message = &#39;雷猴&#39;
</script>

子组件

// Child.vue

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

<script setup>

const props = defineProps({
  msg: {
    type: String,
    default: &#39;&#39;
  }
})

console.log(props.msg) // 在 js 里需要使用 props.xxx 的方式使用。在 html 中使用不需要 props

</script>

<script setup></script> 中必须使用 defineProps API 来声明 props,它具备完整的推断并且在 <script setup></script> 中是直接可用的。

更多细节请看 文档

https://v3.cn.vuejs.org/api/sfc-script-setup.html#defineprops-%E5%92%8C-defineemits

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

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

大家可以去官网看看,这是必须掌握的知识点!

props 文档

https://v3.cn.vuejs.org/guide/component-props.html

emits

子组件通知父组件触发一个事件,并且可以传值给父组件。(简称:子传父)

emits 文档

https://v3.cn.vuejs.org/guide/migration/emits-option.html

Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법

父组件

// Parent.vue

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

<script setup>
import { ref } from &#39;vue&#39;
import Child from &#39;./components/Child.vue&#39;

let message = ref(&#39;雷猴&#39;)

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

子组件

// Child.vue

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

<script setup>

// 注册一个自定义事件名,向上传递时告诉父组件要触发的事件。
const emit = defineEmits([&#39;changeMsg&#39;])

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

</script>

props 一样,在 <script setup></script> 中必须使用 defineEmits API 来声明 emits,它具备完整的推断并且在 <script setup></script> 中是直接可用的。

更多细节请看 文档

https://v3.cn.vuejs.org/api/sfc-script-setup.html#defineprops-%E5%92%8C-defineemits

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

expose / ref

子组件可以通过 expose 暴露自身的方法和数据。

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

expose 文档

https://v3.cn.vuejs.org/api/options-data.html#expose

用例子说话

Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법

父组件

// Parent.vue

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

  <hr>

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

<script setup>
import { ref, onMounted } from &#39;vue&#39;
import Child from &#39;./components/Child.vue&#39;

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

const msg = ref(&#39;&#39;)

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

function callChildFn() {
  // 调用子组件的 changeMessage 方法
  com.value.changeMessage(&#39;蒜头王八&#39;)

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

子组件

// Child.vue

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

<script setup>
import { ref } from &#39;vue&#39;

const message = ref(&#39;蟑螂恶霸&#39;)

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

使用 defineExpose 向外暴露指定的数据和方法
defineExpose({
  message,
  changeMessage
})

</script>

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

  • expose 文档

    https://v3.cn.vuejs.org/api/options-data.html#expose

  • defineExpose 文档

    https://v3.cn.vuejs.org/api/sfc-script-setup.html#defineexpose

Non-Props

所谓的 Non-Props우리 모두 알고 있듯이 Vue.js에서 매우 중요한 지식 포인트는 컴포넌트 통신입니다. 비즈니스 클래스 개발이든 컴포넌트 라이브러리 개발이든 각각 고유한 통신 방법이 있습니다. . [관련 권장사항: vuejs 비디오 튜토리얼]

🎜이 글은 적합 대상: 🎜
  • 🎜Vue 3에 대한 기본 지식이 있는 독자. 🎜
  • 🎜컴포넌트 라이브러리 개발을 계획하고 있는 독자입니다. 🎜
🎜이 기사에서 다루는 지식 포인트: 🎜
  • 🎜Props🎜
  • 🎜emis🎜
  • 🎜노출 / ref🎜
  • 🎜Non-Props🎜
  • 🎜v-model🎜
  • 🎜슬롯 슬롯🎜
  • 🎜제공/주입🎜
  • 🎜bus🎜
  • 🎜getCurrentInstance🎜
  • 🎜Vuex🎜
  • 🎜Pinia🎜 li>
  • 🎜mitt.js🎜
🎜위에 나열된 지식 포인트를 기반으로 간단한 데모를 작성하겠습니다. 이 기사의 목적은 이러한 방법을 사용할 수 있음을 모든 사람에게 알리는 것이므로 모든 지식 포인트를 탐구하지는 않습니다. 🎜🎜독자들은 이 글을 따라 코드를 입력한 다음, 이 글에 제공된 링크를 따라 다양한 지식 포인트를 파헤쳐 보는 것이 좋습니다. 🎜🎜(배운) 컬렉션은 당신의 것입니다! 🎜

Props

🎜상위 구성 요소가 하위 구성 요소에 값을 전달합니다(상위에서 하위로 참조)🎜🎜🎜Props 문서🎜🎜https:// v3.cn.vuejs.org/guide/comComponent-props.html🎜🎜상위 구성 요소
🎜
// Parent.vue

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

<script setup>
import { ref } from &#39;vue&#39;
import Child from &#39;./components/Child.vue&#39;
</script>
🎜하위 구성 요소🎜
// Child.vue

<template>
  <div>子组件:打开控制台看看</div>
</template>
🎜 <script setup></script>defineProps API를 사용하여 props를 선언해야 합니다. 이는 <script setup>에서 완전히 추론되고 사용됩니다. </script> code>를 직접 사용할 수 있습니다. 🎜🎜🎜자세한 내용은 문서를 참조하세요. 🎜🎜https://v3.cn.vuejs.org/api/sfc-script-setup.html#defineprops-%E5%92%8C-defineemits🎜🎜, defineProps를 별도로 도입할 필요는 없습니다. 🎜🎜props는 실제로 기본값 default 설정, 유형 확인 type 요구와 같은 많은 작업을 수행할 수 있습니다. 필수, 사용자 정의 검증 기능 검증기 등이 있습니다. 🎜🎜공식 홈페이지에 가시면 꼭 숙지하셔야 할 지식 포인트입니다! 🎜🎜🎜props 문서🎜🎜https://v3.cn.vuejs.org/guide/comComponent-props.html🎜

방출

🎜sub 구성 요소는 상위 구성 요소에 이벤트를 트리거하도록 알리고 해당 값을 상위 구성 요소에 전달할 수 있습니다. (약어: 아들이 아버지에게 물려줌)🎜🎜🎜문서를 발행합니다🎜🎜https://v3.cn.vuejs.org/guide/migration/emits-option.html🎜🎜Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법🎜🎜상위 구성 요소🎜
// Child.vue

<template>
  <div>子组件:打开控制台看看</div>
  <div>子组件:打开控制台看看</div>
</template>
🎜하위 구성요소🎜
// Child.vue

<template>
  <div :message="$attrs.msg">只绑定指定值</div>
  <div v-bind="$attrs">全绑定</div>
</template>
🎜 props와 동일, defineEmits<script setup>에서 사용해야 합니다. code> > <code>emis</script>를 선언하는 API입니다. 이는 <script setup></script>에서 완전히 추론되고 직접 사용할 수 있습니다. 🎜🎜🎜자세한 내용은 문서를 참조하세요. 🎜🎜https://v3.cn.vuejs.org/api/sfc-script-setup.html#defineprops-%E5%92%8C-defineemits🎜🎜, defineEmits를 별도로 도입할 필요는 없습니다. 🎜

expose / ref

🎜하위 구성 요소는 expose를 통해 자체 메서드와 데이터를 노출할 수 있습니다. 🎜🎜상위 구성 요소는 ref를 통해 하위 구성 요소를 얻고 해당 메서드를 호출하거나 데이터에 액세스합니다. 🎜🎜🎜문서 노출🎜🎜https://v3.cn.vuejs.org/api/options-data.html#expose🎜🎜예제 사용🎜🎜Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법🎜🎜상위 구성 요소🎜
// Parent.vue

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

<script setup>
import { ref } from &#39;vue&#39;
import Child from &#39;./components/Child.vue&#39;

const message = ref(&#39;雷猴&#39;)
</script>
🎜 하위 구성 요소🎜
// Child.vue

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

<script setup>
import { ref } from &#39;vue&#39;

// 接收
const props = defineProps([
  &#39;modelValue&#39; // 接收父组件使用 v-model 传进来的值,必须用 modelValue 这个名字来接收
])

const emit = defineEmits([&#39;update:modelValue&#39;]) // 必须用 update:modelValue 这个名字来通知父组件修改值

function handleClick() {
  // 参数1:通知父组件修改值的方法名
  // 参数2:要修改的值
  emit(&#39;update:modelValue&#39;, &#39;喷射河马&#39;)
}

</script>
🎜 <script setup></script>에서 defineExpose를 별도로 도입할 필요는 없습니다. 🎜🎜
  • 🎜문서 노출🎜🎜https://v3.cn.vuejs.org/api/options-data.html#expose🎜
  • 🎜defineExpose 문서🎜🎜https://v3.cn.vuejs.org/api/sfc-script-setup.html#defineexpose🎜

Non-Props

🎜소위 Non-Prop은 🎜Non-Prop 속성🎜입니다. 🎜

意思是在子组件中,没使用 propemits 定义的 attribute,可以通过 $attrs 来访问。

常见的有 classstyleid

还是举个例子会直观点

单个根元素的情况

父组件

// Parent.vue

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

<script setup>
import { ref } from &#39;vue&#39;
import Child from &#39;./components/Child.vue&#39;
</script>

子组件

// Child.vue

<template>
  <div>子组件:打开控制台看看</div>
</template>

Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법

打开控制台可以看到,属性被挂到 HTML 元素上了。

多个元素的情况

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

// Child.vue

<template>
  <div>子组件:打开控制台看看</div>
  <div>子组件:打开控制台看看</div>
</template>

Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법

此时可以使用 $attrs 的方式进行绑定。

// Child.vue

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

Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법

v-model

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

单值的情况

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

v-model 参数文档

https://v3.cn.vuejs.org/guide/component-custom-events.html#v-model-%E5%8F%82%E6%95%B0

父组件

// Parent.vue

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

<script setup>
import { ref } from &#39;vue&#39;
import Child from &#39;./components/Child.vue&#39;

const message = ref(&#39;雷猴&#39;)
</script>

子组件

// Child.vue

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

<script setup>
import { ref } from &#39;vue&#39;

// 接收
const props = defineProps([
  &#39;modelValue&#39; // 接收父组件使用 v-model 传进来的值,必须用 modelValue 这个名字来接收
])

const emit = defineEmits([&#39;update:modelValue&#39;]) // 必须用 update:modelValue 这个名字来通知父组件修改值

function handleClick() {
  // 参数1:通知父组件修改值的方法名
  // 参数2:要修改的值
  emit(&#39;update:modelValue&#39;, &#39;喷射河马&#39;)
}

</script>

Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법

你也可以这样写,更加简单

子组件

// Child.vue

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

<script setup>
import { ref } from &#39;vue&#39;

// 接收
const props = defineProps([
  &#39;modelValue&#39; // 接收父组件使用 v-model 传进来的值,必须用 modelValue 这个名字来接收
])

</script>

多个 v-model 绑定

多个 v-model 绑定 文档

https://v3.cn.vuejs.org/guide/component-custom-events.html#%E5%A4%9A%E4%B8%AA-v-model-%E7%BB%91%E5%AE%9A

父组件

// Parent.vue

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

<script setup>
import { ref } from &#39;vue&#39;
import Child from &#39;./components/Child.vue&#39;

const message1 = ref(&#39;雷猴&#39;)

const message2 = ref(&#39;蟑螂恶霸&#39;)
</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 &#39;vue&#39;

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

const emit = defineEmits([&#39;update:msg1&#39;, &#39;update:msg2&#39;])

function changeMsg1() {
  emit(&#39;update:msg1&#39;, &#39;鲨鱼辣椒&#39;)
}

function changeMsg2() {
  emit(&#39;update:msg2&#39;, &#39;蝎子莱莱&#39;)
}

</script>

Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법

v-model 修饰符

v-model 还能通过 . 的方式传入修饰。

v-model 修饰符 文档

https://v3.cn.vuejs.org/guide/component-custom-events.html#%E5%A4%84%E7%90%86-v-model-%E4%BF%AE%E9%A5%B0%E7%AC%A6

父组件

// Parent.vue

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

<script setup>
import { ref } from &#39;vue&#39;
import Child from &#39;./components/Child.vue&#39;

const message = ref(&#39;hello&#39;)
</script>

子组件

// Child.vue

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

<script setup>
import { ref, onMounted } from &#39;vue&#39;

const props = defineProps([
  &#39;modelValue&#39;,
  &#39;modelModifiers&#39;
])

const emit = defineEmits([&#39;update:modelValue&#39;])

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

</script>

Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법

插槽 slot

插槽可以理解为传一段 HTML 片段给子组件。子组件将 <slot></slot> 元素作为承载分发内容的出口。

插槽 文档

https://v3.cn.vuejs.org/guide/component-slots.html

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

默认插槽

插槽的基础用法非常简单,只需在 子组件 中使用 <slot></slot> 标签,就会将父组件传进来的 HTML 内容渲染出来。

默认插槽 文档

https://v3.cn.vuejs.org/guide/component-slots.html#%E6%8F%92%E6%A7%BD%E5%86%85%E5%AE%B9

父组件

// Parent.vue

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

子组件

// Child.vue

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

具名插槽

具名插槽 就是在 默认插槽 的基础上进行分类,可以理解为对号入座。

具名插槽 文档

https://v3.cn.vuejs.org/guide/component-slots.html#%E5%85%B7%E5%90%8D%E6%8F%92%E6%A7%BD

Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법

父组件

// 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></template> 标签,并在标签上使用 v-solt: + 名称

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

这就是 对号入座

最后需要注意的是,插槽内容的排版顺序,是 以子组件里的排版为准

上面这个例子就是这样,你可以仔细观察子组件传入顺序和子组件的排版顺序。

作用域插槽

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

作用域插槽 文档

https://v3.cn.vuejs.org/guide/component-slots.html#%E4%BD%9C%E7%94%A8%E5%9F%9F%E6%8F%92%E6%A7%BD

Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법

父组件

// 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 &#39;vue&#39;
import Child from &#39;./components/Child.vue&#39;

const list = ref([
  { name: &#39;雷猴&#39;, occupation: &#39;打雷&#39;},
  { name: &#39;鲨鱼辣椒&#39;, occupation: &#39;游泳&#39;},
  { name: &#39;蟑螂恶霸&#39;, occupation: &#39;扫地&#39;},
])
</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 文档

https://v3.cn.vuejs.org/guide/component-provide-inject.html

1Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법

父组件

// Parent.vue

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

<script setup>
import { ref, provide, readonly } from &#39;vue&#39;
import Child from &#39;./components/Child.vue&#39;

const name = ref(&#39;猛虎下山&#39;)
const msg = ref(&#39;雷猴&#39;)

// 使用readonly可以让子组件无法直接修改,需要调用provide往下传的方法来修改
provide(&#39;name&#39;, readonly(name))

provide(&#39;msg&#39;, msg)

provide(&#39;changeName&#39;, (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 &#39;vue&#39;

const name = inject(&#39;name&#39;, &#39;hello&#39;) // 看看有没有值,没值的话就适用默认值(这里默认值是hello)
const msg = inject(&#39;msg&#39;)
const changeName = inject(&#39;changeName&#39;)

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

  // 正确的方式
  changeName(&#39;虎躯一震&#39;)

  // 因为 msg 没被 readonly 过,所以可以直接修改值
  msg.value = &#39;世界&#39;
}
</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 &#39;vue&#39;

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

  // 订阅
  $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 &#39;vue&#39;
import Bus from &#39;./Bus.js&#39;
import Child from &#39;./components/Child.vue&#39;

const msg = ref(Bus.msg)

const message = ref(&#39;hello&#39;)

// 用监听的写法
Bus.$on(&#39;changeMsg&#39;, 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 &#39;../Bus.js&#39;

function handleBusEmit() {
  Bus.$emit(&#39;changeMsg&#39;, &#39;雷猴啊&#39;)
}

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

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

getCurrentInstance

getcurrentinstancevue 提供的一个方法,支持访问内部组件实例。

getCurrentInstance 只暴露给高阶使用场景,典型的比如在库中。强烈反对在应用的代码中使用 getCurrentInstance。请不要把它当作在组合式 API 中获取 this 的替代方案来使用。

说白了,这个方法 适合在开发组件库的情况下使用,不适合日常业务开发中使用。

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

getcurrentinstance 文档

https://v3.cn.vuejs.org/api/composition-api.html#getcurrentinstance

<script setup></script> 中,我模拟了类似 $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 &#39;vue&#39;
import Child from &#39;./components/Child.vue&#39;

const message = ref(&#39;雷猴啊&#39;)

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(&#39;组件实例:&#39;, item)
      console.log(&#39;组件名(name):&#39;, item.type.name)
      console.log(&#39;组件输入框的值:&#39;, item.devtoolsRawSetupState.inputValue)
      console.log(&#39;---------------------------------------&#39;)
    })
  }
}

</script>

子组件

// Child.vue

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

<script>
export default {
  name: &#39;ccccc&#39;
}
</script>

<script setup>
import { getCurrentInstance, onMounted, nextTick, ref } from &#39;vue&#39;

const inputValue = ref(&#39;&#39;)

let instance = null

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

})

function handleClick() {
  let msg = instance.parent.devtoolsRawSetupState.message
  msg.value = &#39;哈哈哈哈哈哈&#39;
}

</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 &#39;vuex&#39;

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 &#39;vue&#39;
import App from &#39;./App.vue&#39;
import store from &#39;./store&#39;

const app = createApp(App)

app
  .use(store)
  .mount(&#39;#app&#39;)

State

store/index.js

// store/index.js

import { createStore } from &#39;vuex&#39;

export default createStore({
  state: {
    msg: &#39;雷猴&#39;
  }
})

组件

// xxx.vue

<script setup>
import { useStore } from &#39;vuex&#39;

const store = useStore()

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

Getter

我觉得 Getter 方法和 computed 是有点像的。

比如我们需要过滤一下数据,或者返回时组装一下数据,都可以用 Getter 方法。

store/index.js

// store/index.js

import { createStore } from &#39;vuex&#39;

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

组件

// xxx.vue

<script setup>
import { useStore } from &#39;vuex&#39;

const store = useStore()

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

Mutation

Mutation 是修改 State 数据的唯一方法,这样 Vuex 才可以跟踪数据流向。

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

store/index.js

// store/index.js

import { createStore } from &#39;vuex&#39;

export default createStore({
  state: {
    msg: &#39;雷猴&#39;
  },
  mutations: {
    changeMsg(state, data) {
      state.msg = data
    }
  }
})

组件

// xxx.vue

<script setup>
import { useStore } from &#39;vuex&#39;

const store = useStore()

store.commit(&#39;changeMsg&#39;, &#39;蒜头王八&#39;)

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

Action

我习惯将异步的东西放在 Action 方法里写,然后在组件使用 dispatch 方法调用。

store/index.js

// store/index.js

import { createStore } from &#39;vuex&#39;

export default createStore({
  state: {
    msg: &#39;雷猴&#39;
  },
  mutations: {
    changeMsg(state, data) {
      state.msg = data
    }
  },
  actions: {
    fetchMsg(context) {
      // 模拟ajax请求
      setTimeout(() => {
        context.commit(&#39;changeMsg&#39;, &#39;鲨鱼辣椒&#39;)
      }, 1000)
    }
  }
})

组件

// xxx.vue

<script setup>
import { useStore } from &#39;vuex&#39;

const store = useStore()

store.dispatch(&#39;fetchMsg&#39;)
</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 &#39;vuex&#39;
import user from &#39;./modules/user&#39;
import goods from &#39;./modules/goods&#39;

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 还有各种语法糖,大家可以自行查阅 官方文档(https://vuex.vuejs.org/zh/)

Pinia

Pinia 是最近比较火热的一个工具,也是用来处理 跨组件通信 的,极大可能成为 Vuex 5

Pinia 文档

https://pinia.vuejs.org/

从我使用 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 &#39;pinia&#39;

const store = createPinia()

export default store

user.js

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

import { defineStore } from &#39;pinia&#39;

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


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

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

src/main.js

import { createApp } from &#39;vue&#39;
import App from &#39;./App.vue&#39;
import store from &#39;./store&#39;

const app = createApp(App)

app
  .use(store)
  .mount(&#39;#app&#39;)

在组件中使用

组件

// xxx.vue

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

<script setup>
import { computed } from &#39;vue&#39;
import { storeToRefs } from &#39;pinia&#39;
import { useUserStore } from &#39;@/store/user&#39;

const userStore = useUserStore()

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

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


function handleClick() {
  // 不建议这样改
  // name.value = &#39;蝎子莱莱&#39;

  // 推荐的写法!!!
  userStore.updateName(&#39;李四&#39;)
}
</script>

啰嗦两句

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

Pinia 还提供了多种语法糖,强烈建议阅读一下 官方文档(https://pinia.vuejs.org/)。

mitt.js

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

比如:

  • on:添加事件
  • emit:执行事件
  • off:移除事件
  • clear:清除所有事件

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

  • github 地址:https://github.com/developit/mitt

  • npm 地址:https://www.npmjs.com/package/mitt

安装

npm i mitt

使用

我模拟一下 总线Bus 的方式。

我在同级目录创建3个文件用作模拟。

Parent.vue
Child.vue
Bus.js

Bus.js

// Bus.js

import mitt from &#39;mitt&#39;
export default mitt()

Parent.vue

// Parent.vue

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

<script setup>
import Child from &#39;./Child.vue&#39;
import Bus from &#39;./Bus.js&#39;

Bus.on(&#39;sayHello&#39;, () => console.log(&#39;雷猴啊&#39;))
</script>

Child.vue

// Child.vue

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

<script setup>
import Bus from &#39;./Bus.js&#39;

function handleClick() {
  Bus.emit(&#39;sayHello&#39;)
}
</script>

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

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

(学习视频分享:vuejs教程web前端

위 내용은 Vue3 구성 요소 간에 통신하는 방법은 무엇입니까? 공유할 수 있는 10가지 이상의 커뮤니케이션 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
이 기사는 掘金社区에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제
vue.js vs. React : 확장 성과 유지 가능성vue.js vs. React : 확장 성과 유지 가능성May 10, 2025 am 12:24 AM

vue.js와 반응은 각각 확장 성과 유지 가능성에 고유 한 장점이 있습니다. 1) vue.js는 사용하기 쉽고 소규모 프로젝트에 적합합니다. Composition API는 대규모 프로젝트의 유지 보수성을 향상시킵니다. 2) RECT는 크고 복잡한 프로젝트에 적합하며, 후크와 가상 DOM은 성능과 유지 관리를 향상시킬 수 있지만 학습 곡선은 더 가파릅니다.

vue.js and React의 미래 : 트렌드와 예측vue.js and React의 미래 : 트렌드와 예측May 09, 2025 am 12:12 AM

vue.js 및 React의 미래 추세와 예측은 다음과 같습니다. 1) vue.js는 엔터프라이즈 레벨 애플리케이션에서 널리 사용되며 서버 측 렌더링 및 정적 사이트 생성에서 획기적인 결과를 얻었습니다. 2) RECT는 서버 구성 요소 및 데이터 수집에서 혁신하고 동시성 모델을 더욱 최적화합니다.

Netflix의 프론트 엔드 : 기술 스택에 대한 깊은 다이빙Netflix의 프론트 엔드 : 기술 스택에 대한 깊은 다이빙May 08, 2025 am 12:11 AM

Netflix의 프론트 엔드 기술 스택은 주로 React 및 Redux를 기반으로합니다. 1. 반응은 고성능 단일 페이지 응용 프로그램을 구축하는 데 사용되며 구성 요소 개발을 통해 코드 재사용 성 및 유지 보수를 향상시킵니다. 2. Redux는 상태 변경이 예측 가능하고 추적 할 수 있도록 국가 관리에 사용됩니다. 3. 도구 체인에는 코드 품질과 성능을 보장하기위한 웹 팩, 바벨, 농담 및 효소가 포함됩니다. 4. 성능 최적화는 코드 세분화, 게으른로드 및 서버 측 렌더링을 통해 사용자 경험을 향상시킵니다.

vue.js 및 프론트 엔드 : 대화식 사용자 인터페이스 구축vue.js 및 프론트 엔드 : 대화식 사용자 인터페이스 구축May 06, 2025 am 12:02 AM

vue.js는 대화 형 사용자 인터페이스를 구축하는 데 적합한 점진적인 프레임 워크입니다. 핵심 기능에는 응답 시스템, 구성 요소 개발 및 라우팅 관리가 포함됩니다. 1) 응답 시스템은 Object.DefineProperty 또는 프록시를 통한 데이터 모니터링을 실현하고 인터페이스를 자동으로 업데이트합니다. 2) 구성 요소 개발을 통해 인터페이스를 재사용 가능한 모듈로 분할 할 수 있습니다. 3) Vuerouter는 단일 페이지 응용 프로그램을 지원하여 사용자 경험을 향상시킵니다.

vuejs의 단점은 무엇입니까?vuejs의 단점은 무엇입니까?May 05, 2025 am 12:06 AM

vue.js의 주요 단점은 다음과 같습니다. 1. 생태계는 비교적 새롭고 타사 라이브러리와 도구는 다른 프레임 워크만큼 풍부하지 않습니다. 2. 학습 곡선은 복잡한 기능에서 가파르게됩니다. 3. 지역 사회 지원과 자원은 반응과 각도만큼 광범위하지 않다. 4. 대규모 응용 프로그램에서 성능 문제가 발생할 수 있습니다. 5. 버전 업그레이드 및 호환성 문제가 더 큽니다.

Netflix : 프론트 엔드 프레임 워크를 공개합니다Netflix : 프론트 엔드 프레임 워크를 공개합니다May 04, 2025 am 12:16 AM

Netflix는 React를 프론트 엔드 프레임 워크로 사용합니다. 1. 반응의 구성 요소 개발 및 가상 DOM 메커니즘은 성능 및 개발 효율성을 향상시킵니다. 2. Webpack 및 Babel을 사용하여 코드 구성 및 배포를 최적화하십시오. 3. 성능 최적화를 위해 코드 세분화, 서버 측 렌더링 및 캐싱 전략을 사용하십시오.

vue.js의 프론트 엔드 개발 : 장점과 기술vue.js의 프론트 엔드 개발 : 장점과 기술May 03, 2025 am 12:02 AM

vue.js의 인기에는 단순성과 쉬운 학습, 유연성 및 고성능이 포함됩니다. 1) Progressive Framework 설계는 초보자가 단계별로 학습하는 데 적합합니다. 2) 구성 요소 기반 개발은 코드 유지 관리 및 팀 협업 효율성을 향상시킵니다. 3) 반응 형 시스템과 가상 DOM은 렌더링 성능을 향상시킵니다.

vue.js vs. React : 사용 편의성 및 학습 곡선vue.js vs. React : 사용 편의성 및 학습 곡선May 02, 2025 am 12:13 AM

vue.js는 사용하기 쉽고 부드러운 학습 곡선이 있으며 초보자에게 적합합니다. React는 더 가파른 학습 곡선을 가지고 있지만 유연성이 강하기 때문에 숙련 된 개발자에게 적합합니다. 1. vue.js는 간단한 데이터 바인딩 및 프로그레시브 디자인을 통해 쉽게 시작할 수 있습니다. 2. 반응은 Virtual DOM 및 JSX에 대한 이해가 필요하지만 유연성과 성능 이점이 높아집니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구