Based on Vue 2.x, the communication modes of components are sorted out and divided into the following four categories:
- Built-in class
- Wrapper class
- The third party class
- other
Built-in class
way | instructions | advantages | disadvantages | chestnuts |
---|---|---|---|---|
$ref  / $parent / $children / $root |
Avoid accessing $refs in templates or computed properties | Facilitates simple father-son communication | Not father and son, easy to lose control | |
prop & $emit | The child component gets the data from the props, and the $emit fires the event; The parent component listens for events triggered by the child component through v-ON binding events | Commonly used father-son communication | Not conducive to cross-level communication | |
Provide & Inject | The parent component provide provides data/methods to all of its child components, while the child component inject inject data/methods, which can be seen as a broad valid prop | The cross level | 1, non-responsive, the parent value changes but the child value remains the original value; 2. High coupling, difficult reconstruction, high universality before use | “Element”Github.com/ElemeFE/ele… |
Mixins/extends (mixins/inheritance) | Mixins: Distribute reusable functions in Vue components; Extends: Extends a single-file component, similar to mixins | To facilitate the separation of different logic into different JS files, mixins can be multiple | 1. Conflict of the same name; 2. Implied dependencies. There is no hierarchy between mixins and the components that use them | “Element”Github.com/ElemeFE/ele… |
$attrs | Contains attribute bindings (except class and style) that the parent scope is not identified (and retrieved) as a prop | Pass in the internal component via v-bind=”$attrs” | “Element”Github.com/ElemeFE/ele… | |
$listeners | Contains a V-on event listener in the parent scope (without the.native modifier) | Pass in internal components via V-ON =”$Listeners” |
Wrapper class
way | instructions | advantages | disadvantages | chestnuts |
---|---|---|---|---|
Broadcast & Dispatch | Find the specified component by recursion or traversal (up/down), and then on the component itself$emit with$on To achieve cross-level communication |
Cross-class, easy to use | Communication between sibling components is not resolved | “Element”Github.com/ElemeFE/ele… |
vm.broadcast(componentName, eventName, params) // Called on the parent component, traversing down the child nodes
vm.dispatch(componentName, eventName, params) // Called on the child component, traversing up the parent nodeVm. $on (eventName, callback)// The parent component is called to listen for the event (mounted).Vm. $off (eventName, callback)// Called in the parent component to remove the corresponding event listener (usually in beforeDestroy)
Copy the code
way | instructions | advantages | disadvantages | chestnuts |
---|---|---|---|---|
FindComponents series of methods | See below | Finds the parent, child, or sibling of the specified component | “The view – the design”Github.com/view-design… |
findComponentUpward(this,componentName) // Go up to the nearest specified component
findComponentsUpward(this,componentName) // Go up to find all the specified components
findComponentDownward(this,componentName) // Go down to the nearest specified component
findComponentsDownward(this,componentName) // Go down to all the specified components
findBrothersComponents(this,componentName,exceptMe = true) ExceptMe: specifies whether to exceptMe itself
Copy the code
The third party class
way | instructions | advantages | disadvantages | chestnuts |
---|---|---|---|---|
Vuex | A state management pattern developed specifically for vue.js applications | 1. Solved the messaging of non-parent and child components; 2. Reduced the number of requests; 3, belong to the VUE ecology, can respond to trigger the rendering page update; 4. Ensure that the state changes in a predictable way | Not suitable for simple applications |
state
Storing state variables
$sotre.state.xxx
/ $sotre.state.someModulesName.xxx
Corresponding auxiliary function: mapState
getter
Think of it as a evaluated property of store. The return value of a getter is cached according to its dependencies and is only recalculated if its dependencies change
$sotre.getters.xxx
 / $sotre.getters.xxx(params)
Corresponding helper function: mapGetters
mutations
Synchronizes the modification state, similar to custom events in a component
$store.commit('xxx', params)
Corresponding auxiliary function: mapMutations
actions
Asynchronous operations, which do not directly operate on state, but on mutation, similar to axios requests, can be written in action
$store.dispath('xxx', params)
Corresponding helper function: mapActions
modules
A submodule of store, used for developing large projects to facilitate state management
getters:Â {
    checkedList: (state) = > {
      return state.dataList.filter(f= > f.checked);
    },
    checkedListLength: (state, getters) = > {
      return getters.checkedList.length;
    },
    listLabelById: (state) = > (id) = > {
      return state.dataList.find(f= >f.id == id).label; Mutations: {mutations: {setUserToken(state, value) {
    state.userToken = value;
  },
  setTmpObj(state, params){ Vue.set(state.tmpMsg, params.key, params.value); }} actions: {toLogin({commit}, params) {
    // Simulate asynchronous requests
    API.login(params, (res) = > {
      if (res) {
        commit('setUserToken', res.data.token)Â
      }
    })
  }
}
Copy the code
other
way | instructions | advantages | disadvantages | chestnuts |
---|---|---|---|---|
EventBus/eventHub | Add a Vue object,eventBus.$emit Trigger event;eventBus.$on Listening event;eventBus.$off Destroy listen event |
The cross level | If you want to listen to only one event, manually destroy the listener to avoid repeated creation next time | See below |
// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()Â
/ / or main. Js
Vue.prototype.$EventBus = new Vue()
/ / or main. Js
const eventBus = new Vue();
new Vue({
  el: '#app'.data() {
    return { bus: eventBus }
  },
  components: { App },
  template: '<App/>'
})
this. $root. Bus. $emit (eventName, args [...])this.$root.bus.$on(eventName, callback)Â
Copy the code
Last but not least
If there is anything wrong, please let me know