当前位置: 首页 > news >正文

vue基础(八)

在 Vue 中,组件之间的传值方式主要包括以下几种情况:

1. 父组件向子组件传值(props

父组件通过 props 传递数据给子组件:

<!-- Parent.vue -->
<template>
  <ChildComponent :msg="message" />
</template>

<script>
import ChildComponent from './ChildComponent.vue';
export default {
  components: { ChildComponent },
  data() {
    return {
      message: 'Hello from Parent!'
    };
  }
};
</script>
<!-- ChildComponent.vue -->
<template>
  <p>Received message: {{ msg }}</p>
</template>

<script>
export default {
  props: {
    msg: String
  }
};
</script>

2. 子组件向父组件传值($emit

子组件通过 this.$emit 触发事件,父组件监听事件并获取值:

<!-- Parent.vue -->
<template>
  <ChildComponent @update-message="handleMessage" />
  <p>Message from Child: {{ receivedMessage }}</p>
</template>

<script>
import ChildComponent from './ChildComponent.vue';
export default {
  components: { ChildComponent },
  data() {
    return {
      receivedMessage: ''
    };
  },
  methods: {
    handleMessage(msg) {
      this.receivedMessage = msg;
    }
  }
};
</script>
<!-- ChildComponent.vue -->
<template>
  <button @click="sendMessage">Send to Parent</button>
</template>

<script>
export default {
  methods: {
    sendMessage() {
      this.$emit('update-message', 'Hello from Child!');
    }
  }
};
</script>

3. 兄弟组件传值(Event BusPinia/Vuex

兄弟组件需要一个中间桥梁,比如 Event Bus(Vue 3 不推荐)或 Pinia(推荐):

// eventBus.js (Vue 2 可用,Vue 3 推荐使用 Pinia)
import Vue from 'vue';
export const EventBus = new Vue();

BrotherA.vue 发送数据:

<template>
  <button @click="sendMessage">Send to BrotherB</button>
</template>

<script>
import { EventBus } from './eventBus.js';
export default {
  methods: {
    sendMessage() {
      EventBus.$emit('message', 'Hello from BrotherA!');
    }
  }
};
</script>

BrotherB.vue 接收数据:

<template>
  <p>{{ receivedMessage }}</p>
</template>

<script>
import { EventBus } from './eventBus.js';
export default {
  data() {
    return { receivedMessage: '' };
  },
  created() {
    EventBus.$on('message', msg => {
      this.receivedMessage = msg;
    });
  }
};
</script>

4. ref 方式(获取子组件实例)

父组件可以通过 ref 获取子组件实例并访问其方法或数据:

<!-- Parent.vue -->
<template>
  <ChildComponent ref="childRef" />
  <button @click="callChildMethod">Call Child Method</button>
</template>

<script>
import ChildComponent from './ChildComponent.vue';
export default {
  components: { ChildComponent },
  methods: {
    callChildMethod() {
      this.$refs.childRef.childMethod();
    }
  }
};
</script>
<!-- ChildComponent.vue -->
<template>
  <p>Child Component</p>
</template>

<script>
export default {
  methods: {
    childMethod() {
      console.log('Child method called!');
    }
  }
};
</script>

5. provideinject(适用于祖孙组件)

适用于跨层级组件通信:

<!-- GrandParent.vue -->
<template>
  <Parent />
</template>

<script>
import Parent from './Parent.vue';
export default {
  components: { Parent },
  provide() {
    return { sharedMessage: 'Hello from GrandParent!' };
  }
};
</script>
<!-- Parent.vue -->
<template>
  <Child />
</template>

<script>
import Child from './Child.vue';
export default {
  components: { Child }
};
</script>
<!-- Child.vue -->
<template>
  <p>{{ sharedMessage }}</p>
</template>

<script>
export default {
  inject: ['sharedMessage']
};
</script>

6. Vuex 或 Pinia(全局状态管理)

适用于复杂状态管理,如 Vuex(Vue 2)或 Pinia(Vue 3):

// store.js (使用 Pinia)
import { defineStore } from 'pinia';

export const useMainStore = defineStore('main', {
  state: () => ({
    message: 'Hello from Store'
  }),
  actions: {
    setMessage(newMsg) {
      this.message = newMsg;
    }
  }
});

ComponentA.vue 更新数据:

<template>
  <button @click="updateMessage">Update Message</button>
</template>

<script>
import { useMainStore } from './store.js';
export default {
  setup() {
    const store = useMainStore();
    const updateMessage = () => store.setMessage('Updated Message!');
    return { updateMessage };
  }
};
</script>

ComponentB.vue 读取数据:

<template>
  <p>{{ store.message }}</p>
</template>

<script>
import { useMainStore } from './store.js';
export default {
  setup() {
    const store = useMainStore();
    return { store };
  }
};
</script>

相关文章:

  • 2848、与车相交的点
  • 游戏引擎学习第103天
  • [FastAdmin] 上传图片并加水印,压缩图片
  • 重读《Java面试题,10万字208道Java经典面试题总结(附答案)》
  • 一种 SQL Server 数据库恢复方案:解密、恢复并导出 MDF/NDF/BAK文件
  • 【Elasticsearch】Mapping概述
  • 适用于iOS的应用商店优化(ASO)清单
  • Qt信号槽调用出错:Qt: Dead lock detected while activating a BlockingQueuedConnection
  • Anaconda 安装指南:Windows、macOS 和 Linux 的详细安装步骤
  • 轮子项目--消息队列的实现(3)
  • Redis初阶笔记
  • 【Linux】cron计划任务定时执行命令
  • 问界M8细节曝光,L3自动驾驶有了!
  • 【LeetCode】394. 字符串解码
  • Windows中指定路径安装DockerDesktop
  • 02、QLExpress从入门到放弃,相关API和文档
  • Electron:使用electron-react-boilerplate创建一个react + electron的项目
  • 回顾Golang的Channel与Select第一篇
  • Anaconda +Jupyter Notebook安装(2025最新版)
  • 【C】初阶数据结构5 -- 栈
  • 湖北十堰市委副秘书长管聪履新丹江口市代市长
  • 五一假期,长三角铁路张家港、台州等多个车站客发量创新高
  • 公安部:“五一”假期全国社会大局稳定,治安秩序良好
  • 特朗普要征100%关税,好莱坞这批境外摄制新片有麻烦了
  • 韩国总统选举民调:共同民主党前党首李在明支持率超46%
  • 2类药物别乱吃,严重可致肝肾衰竭!多人已中招