Vue组件间数据传递

props传递数据

父组件向子组件传递数据,传递的数据只读

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  }
}
<template>
  <HelloWorld msg="Welcome to Your Vue.js App"/>
</template>

定义事件

子组件向父组件传递数据

export default {
  name: 'SendHello',
  data() {
    return {
      item: 'hello'
    }
  },
  methods: {
    sendMessage() {
      this.$emit('send', this.item);
    }
  }
}
<template>
  <SendHello @send="handleSend"/>
</template>

事件总线

不同组件传递数据的通用方法

初始化事件总线

// main.js
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  beforeCreate() {
    // 初始化
    Vue.prototype.$bus = this;
  }
}).$mount('#app')
export default {
  name: 'Search',
  data() {
    return {
      searchText: ''
    }
  },
  methods: {
    search() {
      // 使用事件总线触发事件
      this.$bus.$emit('sendSearch');
      axios.get(`https://api.github.com/search/users?q=${this.searchText}`).then(response => {
        this.$bus.$emit('searchSuccess', response.data.items);
      }).catch(error => {
        this.$bus.$emit('searchError', error.message);
      });
    }
  }
}
export default {
  name: 'List',
  data() {
    return {
      items: [],
      showWelcome: true,
      showLoading: false,
      errorMessage: '',
      sponsor: ['MIT', 'Harvard', 'GitHub']
    }
  },
  methods: {
    // 事件处理
    handleSearchSuccess(items) {
      this.showLoading = false;
      this.items = items;
    },
    handleSendSearch() {
      this.showWelcome = false;
      this.showLoading = true;
      this.items = [];
      this.errorMessage = '';
    },
    handleSearchError(errorMessage) {
      this.showLoading = false;
      this.errorMessage = errorMessage;
    }
  },
  created() {
    // 绑定事件
    this.$bus.$on('searchSuccess', this.handleSearchSuccess);
    this.$bus.$on('sendSearch', this.handleSendSearch);
    this.$bus.$on('searchError', this.handleSearchError);
  },
  beforeDestroy() {
    // 解绑事件
    this.$bus.$off('searchSuccess', this.handleSearchSuccess);
    this.$bus.$off('sendSearch', this.handleSendSearch);
    this.$bus.$off('searchError', this.handleSearchError);
  }
}