Vue.js 组件间通信是一个重要的概念,它允许我们在组件之间传递数据和指令。以下是一些常用的组件间通信方式:

1. Props 和 Events

Props 是父组件向子组件传递数据的方式,而 Events 则是子组件向父组件传递信息的方式。

  • 使用 Props 传递数据:

    // 父组件
    <ChildComponent :message="message" />
    
    // 子组件
    this.$emit('update:message', newValue);
    
  • 使用 Events 传递数据:

    // 子组件
    this.$emit('my-event', data);
    
    // 父组件
    <ChildComponent @my-event="handleEvent" />
    

2. Vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式和库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

  • 安装 Vuex:

    npm install vuex --save
    
  • 创建 Vuex 实例:

    import Vue from 'vue';
    import Vuex from 'vuex';
    
    Vue.use(Vuex);
    
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment(state) {
          state.count++;
        }
      }
    });
    
    new Vue({
      el: '#app',
      store,
      render: h => h(App)
    });
    

3. $refs

通过 $refs,子组件可以在父组件中直接引用子组件的实例。

// 父组件
<template>
  <ChildComponent ref="child" />
</template>

<script>
export default {
  mounted() {
    this.$refs.child.someMethod();
  }
};
</script>

更多关于 Vue.js 组件间通信的信息,请查看Vue.js 官方文档.

附加资源

[center]Vue_communication