Data communication between Vue components

Time:2022-5-10

Props configuration item

  • Function: let the component accept the data from the outside

    • Transfer data:
    • Accept data:
      • admit of only interpretation
        props: ["name"],
      • Limit type acceptance
        props: {
          name: String,
        },
      • Restriction type, necessity restriction, specify default value, accept
        props: {
          name: {
            type: String,
            required: true,
            Default: "Hu xiansen"
          },
        },
  • Note: props is read-only. Vue bottom layer will monitor your modification of props. If it is modified, it will issue a warning. If the business needs to be modified, please copy the contents of props into data, and then modify the data in data

Custom events for components

  • A way of communication between components, applicable to: child component = = = > parent component

  • Usage scenario: A is the parent component and B is the child component. If B wants to transfer data to a, it needs to bind a custom event to B in a (the callback of the event is in a)

  • Binding custom events

    • In parent component

      perhaps
    • In parent component

      ...
      mounted() {
        this.$refs.student.$on("myClick", this.test);
      }
    • If you want a custom event to be triggered only once, you can use the once modifier or the $once method

  • Trigger custom event: this$ emit(“myClick”, params)

  • Unbind custom event: this$ off(“myClick”)

  • Native DOM events can also be bound on the component, and the native modifier is required. Especially when the element UI component is used, the defined events are generally decorated with native.

  • Note: through this$ refs. student.$ When Binding custom events on (“myclick”, this. Test), the callback is either configured in methods or used as an arrow function, otherwise there will be problems with this pointing!

Global event bus

  • A way of communication between components, which is suitable for communication between any components

  • Install the global event bus (main. JS):

    new Vue({
      ...
      beforeCreate() {
        //Install the global event bus, $bus is the VM of the current application
        Vue.prototype.$bus = this;
      },
      ...
    })
  • Using the global event bus:

    • Accept data: if component a wants to accept data, bind a custom event to $bus in component A, and the callback function of the event remains in component A
      methods: {
        demo(data) {...},
      },
      mounted() {
        this.$bus.$on("xxx", this.demo)
      }
    • Provide data
      this.$bus.$emit("xxx", params)
  • It is better to use $off in the beforedestroy hook to unbind the events used by the current component

Message subscription and Publication (PubSub)

  • A way of communication between components, which is suitable for communication between any components.

  • Use steps:

    • Install PubSub
      npm install --save pubsub-js
    • introduce
      import pubsub from "pubsub-js"
    • Accept data: if component a wants to accept data, it subscribes to messages in component A, and the subscribed callback function remains in component A
      methods: {
        demo(data) {...},
      },
      mounted() {
        this.pubId = pubsub.subscribe("xxx", this.demo);
      }
    • Provide data
      pubsub.publish("xxx", params);
  • It’s best to use it in beforedestroy hook

    pubsub.unsubscribe(this.pubId);

    Unbind the events used by the current component

slot

  • Function: enables the parent component to insert HTML structure into the specified location of the child component. It is also a way of communication between components. It is applicable to parent component = = > child component
  • Category: default slot, named slot, scope slot
    -Usage:
    • Default slot:
      • Parent component:
        HTML structure
      • Sub components:
        Some description
    • Named slot:
      • Parent component:
        HTML structure
          
          
            HTML structure
      • Sub components:
        Some description
            Some description
    • Scope slot:
      • Understanding: the data is in the component itself, but the structure generated by the data needs to be determined by the user of the component. (the Games data is in the category component, but the structure traversed by the data is determined by the app component)

      • Specific implementation:

        • Parent component:
          {{game}}
              
            
            
              
                {{game}}
        • Sub components:
          Some description
          export default {
              name: "Category",
              props: ["title"],
              data() {
                return {
                  Games: ['Red Alert', 'crossing the line of fire', 'strong dance troupe', 'super Mary'],
                }
              },
            }

Vuex (refer to the blogger’s use of vuex and map method)

  • Concept: a Vue plug-in that implements centralized state (data) management in Vue. It centrally manages (reads / writes) the shared state of multiple components in Vue applications. It is also a way of communication between components, and is applicable to the communication between any components

  • Usage scenario: multiple components need to share data

  • Build vuex environment

    • Create file: Src / store / index js
      //This file is used to create the most core store in vuex
      //Introduce vuex
      import Vue from 'vue'
      //Introduce vuex插件
      import Vuex from "vuex"
      Vue.use(Vuex)
      //Prepare actions -- actions used to respond to components
      const actions = {}
      //Prepare mutations -- for manipulating data (state)
      const mutations = {}
      //Prepare state -- for storing data
      const state = {}
      
      const store = new Vuex.Store({
        actions,
        mutations,
        state,
      })
      
      export default store;
    • In main When creating VM in JS, pass in the store configuration item
      //Import the created store
      import store from "./store"
      
      new Vue({
        el: '#app',
        render: h=>h(App),
        //Using store
        store,
        ...
      })
  • Specific use

    • Component use
      methods: {
        add() {
          this.$store.dispatch("add", params);
        },
        ...
      }
    • src/store/index. JS configuration
      //Prepare actions -- actions used to respond to components
      const actions = {
        add(context, value) {
          context.commiit("ADD", value);
        },
        ...
      }
      //Prepare mutations -- for manipulating data (state)
      const mutations = {
        ADD(state, value) {
          state.sum += value;
        },
        ...
      }
      //Prepare state -- for storing data
      const state = {
        sum: 0,
        ...
      }

Recommended Today

About interpersonal relationships

Not long ago, a classmate told me that his interpersonal relationship was very poor since he was a child. Few people in school played well. Usually he was alone. He had long recognized that this situation was bad, but he was also used to it.   But now that I have graduated, I am about […]