全面的前端编程教程 - 秘密武器开发者中心

热搜:m1 代理 前端 301

vue3中几种传参方式,有详细的代码和注释

2022-01-03 23:15:09

vue3中几种传参方式,有详细的代码和注释


在Vue3中,组件间的参数传递主要通过以下几种方式:

  1. 使用Props和Emit传递参数
  2. 使用事件总线Event bus传递参数
  3. 使用vuex管理状态传递参数

下面是相应的代码示例和注释:

  1. Props和Emit传参

父组件:

<template>
  <ChildComponent :msg="message" @getChildMsg="receiveMsg"/>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  // 引入子组件
  components: {
    ChildComponent,
  },
  data() {
    return {
      // 需要传递给子组件的数据
      message: 'Hello, Child Component',
    };
  },
  methods: {
    // 接收子组件通过$emit返回的数据
    receiveMsg(msg) {
      console.log(msg);
    },
  },
};
</script>

 

子组件:

<template>
  <div>
    <h1>{{ msg }}</h1>
    <button @click="sendMsg">Click Me</button>
  </div>
</template>

<script>
export default {
  // 接收父组件传过来的数据
  props: ['msg'],
  methods: {
    sendMsg() {
      // 点击按钮后向父组件返回消息
      this.$emit('getChildMsg', 'This is message from child component');
    },
  },
};
</script>

 
  1. 使用事件总线Event bus传递参数

在Vue3中可以采用mitt库作为事件总线工具,首先在main.js中创建一个全局的eventBus:

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

const eventBus = mitt()
const app = createApp(App)
app.config.globalProperties.eventBus = eventBus
app.mount('#app')
在需要发布事件的组件中,可以通过eventBus触发:
this.eventBus.emit('myEvent', 'Hello EventBus')

在接收事件的组件中,通过eventBus监听事件:

this.eventBus.on('myEvent', (msg) => {
  console.log(msg) // 输出“Hello EventBus”
})

 
  1. 使用Vuex管理状态传递参数

首先需要在store中定义一个状态和一个修改方法:

import { createStore } from 'vuex'

const store = createStore({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

export default store

然后在需要触发修改的组件中,通过vuex的commit方法触发状态的修改:

this.$store.commit('increment')

在需要接收修改后的状态的组件中,通过vuex的state来获取状态:

console.log(this.$store.state.count)