vue3组件通信(8种)

简介: vue3组件通信(8种)

vue3组件通信

props

通过setup语法糖来实现,下面是代码
父组件中
<template>
    <Childs :msg="msg"  :msgs="msgs"></Childs>
</template>
<script setup>
import { ref,reactive } from 'vue';
import Childs from './child.vue'
const msg = ref('这是传递给子组件的')
const msgs = reactive(['这是传递给子组件的'])
</script>
子组件
<template>子组件</template>
<script setup>
const props = defineProps({
    // msg:String
    msgs:{
        type:String,
        default:""
    }
})
console.log(props) //打印一下看能不能接收到
</script>

$emit

通过$emit实现子传父通信
<!-- $emit -->
<!-- Child.vue -->
<template>
    <button @click="handleClick">按钮</button>
</template>
<script setup>
import { defineEmits } from 'vue';
const emit = defineEmits(['myClick']);
const handleClick = () => {
    emit('myClick', '我是子组件的信息');
};
</script>
<!-- Parent.vue -->
<template>
    <child @myClick="onMyClick"></child>
</template>
<script setup>
import Child from './Child.vue';
const onMyClick = (msg) => {
    console.log(msg); // 这是父组件收到的信息
};
</script>

v-model

<!-- Parent.vue -->
<template>
    <div>
      <Child v-model:name="name"></Child>
      <p>{{ name }}</p>
    </div>
 </template>
  <script setup>
  import Child from './Child.vue';
  import { ref } from 'vue';
  const name = ref('111');
  </script>
<!-- Child.vue -->
<template>
   <p>{{ name }}</p>
  </template>
  <script setup>
  import { defineProps, defineEmits } from 'vue';
  const props = defineProps({
    name:String
  });
  </script>

$attrs

使用$attrs实现父组件像子组件传递数据
<!-- Parent.vue -->
<template>
    <Child :msg="msg" title="父组件传递的数据"></Child>
</template>
<script setup>
import Child from "./Child.vue";
import { ref } from "vue";
const msg = ref("我是父组件数据111111");
</script>
<!-- Child.vue -->
<template>
  <div>
    <p>{{ msg }}</p>
    <p>{{ title }}</p>
  </div>
</template>
<script setup>
import { defineProps, useAttrs } from "vue";
const props = defineProps({
  msg: String,
});
const attrs = useAttrs();
const title = attrs.title;
</script>

export/ref

父组件中
<template>
    <div>
      <Child :countRef="countRef" />
    </div>
  </template>
  <script setup>
  import { ref } from 'vue';
  import Child from './child.vue';
  const countRef = ref(0);
  </script>
<template>
  <div>
    子组件计数:{{ count }}
    <button @click="increment">+1</button>
  </div>
</template>
<script setup>
import { exportRef } from 'vue';
export default {
  props: {
    countRef: {
      type: Object,
      required: true,
    },
  },
  // 通过 export 导出 countRef
  setup(props) {
    const count = props.countRef;
    exportRef('count', count);
    const increment = () => {
      count.value++;
    };
    return {
      count,
      increment,
    };
  },
};
</script>

provide/inject

使用provide/inject实现跨层级通信
<!-- Parent.vue -->
<template>
    <div>
        <Child></Child>
    </div>
</template>
<script setup>
import { provide } from 'vue';
import Child from './child.vue';
const message = '我是父组件数据';
provide('message', message);
</script>
<!-- Child.vue -->
<template>
  <div>
    <p>子组件数据:{{ injectedMessage }}</p>
  </div>
</template>
<script setup>
import { inject, ref } from 'vue';
import { provide } from 'vue';
const injectedMessage = inject('message', '默认值');
</script>

vuex

使用vuex实现一个简单的通信需要以下几个步骤
1.下载vuex
npm install vuex
后续是代码
在 store.js 文件中创建 store 对象。
import { createStore } from 'vuex';
const store = createStore({
  state() {
    return {
      count: 0,
    };
  },
  mutations: {
    increment(state) {
      state.count++;
    },
  },
});
export default store;
<template>
  <div>
    <p>计数器:{{ count }}</p>
    <button @click="increment">+1</button>
  </div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
  computed: {
    ...mapState(['count']),
  },
  methods: {
    ...mapMutations(['increment']),
  },
};
</script>

mitt

跟vuex一样首先我们需要下载mitt库
npm install mitt
后续是代码
<template>
  <div>
    <p>计数器:{{ count }}</p>
  </div>
</template>
<script>
export default {
  data() {
    return {
      count: 0,
    };
  },
  created() {
    this.$bus.on('increment', () => {
      this.count++;
    });
  },
};
</script>
<template>
  <div>
    <button @click="increment">+1</button>
  </div>
</template>
<script>
export default {
  methods: {
    increment() {
      this.$bus.emit('increment');
    },
  },
};
</script>

到这里也就结束了

记得点赞哦


相关文章
|
6月前
|
JavaScript
Vue中如何实现兄弟组件之间的通信
在Vue中,兄弟组件可通过父组件中转、事件总线、Vuex/Pinia或provide/inject实现通信。小型项目推荐父组件中转或事件总线,大型项目建议使用Pinia等状态管理工具,确保数据流清晰可控,避免内存泄漏。
547 2
|
5月前
|
JavaScript 前端开发 安全
Vue 3
Vue 3以组合式API、Proxy响应式系统和全面TypeScript支持,重构前端开发范式。性能优化与生态协同并进,兼顾易用性与工程化,引领Web开发迈向高效、可维护的新纪元。(238字)
807 139
|
10月前
|
缓存 JavaScript PHP
斩获开发者口碑!SnowAdmin:基于 Vue3 的高颜值后台管理系统,3 步极速上手!
SnowAdmin 是一款基于 Vue3/TypeScript/Arco Design 的开源后台管理框架,以“清新优雅、开箱即用”为核心设计理念。提供角色权限精细化管理、多主题与暗黑模式切换、动态路由与页面缓存等功能,支持代码规范自动化校验及丰富组件库。通过模块化设计与前沿技术栈(Vite5/Pinia),显著提升开发效率,适合团队协作与长期维护。项目地址:[GitHub](https://github.com/WANG-Fan0912/SnowAdmin)。
1192 5
|
5月前
|
缓存 JavaScript 算法
Vue 3性能优化
Vue 3 通过 Proxy 和编译优化提升性能,但仍需遵循最佳实践。合理使用 v-if、key、computed,避免深度监听,利用懒加载与虚拟列表,结合打包优化,方可充分发挥其性能优势。(239字)
417 1
|
6月前
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
687 11
|
5月前
|
JavaScript 安全
vue3使用ts传参教程
Vue 3结合TypeScript实现组件传参,提升类型安全与开发效率。涵盖Props、Emits、v-model双向绑定及useAttrs透传属性,建议明确声明类型,保障代码质量。
483 0
|
7月前
|
缓存 前端开发 大数据
虚拟列表在Vue3中的具体应用场景有哪些?
虚拟列表在 Vue3 中通过仅渲染可视区域内容,显著提升大数据列表性能,适用于 ERP 表格、聊天界面、社交媒体、阅读器、日历及树形结构等场景,结合 `vue-virtual-scroller` 等工具可实现高效滚动与交互体验。
694 1
|
7月前
|
缓存 JavaScript UED
除了循环引用,Vue3还有哪些常见的性能优化技巧?
除了循环引用,Vue3还有哪些常见的性能优化技巧?
396 0
|
8月前
|
JavaScript
vue3循环引用自已实现
当渲染大量数据列表时,使用虚拟列表只渲染可视区域的内容,显著减少 DOM 节点数量。
194 0
|
10月前
|
JavaScript API 容器
Vue 3 中的 nextTick 使用详解与实战案例
Vue 3 中的 nextTick 使用详解与实战案例 在 Vue 3 的日常开发中,我们经常需要在数据变化后等待 DOM 更新完成再执行某些操作。此时,nextTick 就成了一个不可或缺的工具。本文将介绍 nextTick 的基本用法,并通过三个实战案例,展示它在表单验证、弹窗动画、自动聚焦等场景中的实际应用。
935 17

热门文章

最新文章