Home  >  Article  >  Web Front-end  >  Sharing examples of 4 Vue component communication methods

Sharing examples of 4 Vue component communication methods

小云云
小云云Original
2018-02-07 14:23:242425browse

This article mainly shares with you four Vue component communication methods: communication between parent and child components, eventBus communication between non-parent and child components, component communication using local cache, and Vuex communication. Hope it helps everyone.

The first communication method: parent-child component communication

The parent component passes data to the child component

  • The parent component needs to do a total of 4 things Things

    • 1.import son from './son.js' Register all sub-component names in "son"}

    • 3. Apply the sub-component in the template of the parent component,

    • 4. If you need to pass data to the subcomponent, write

    • in the template

       // 1.引入子组件 
           import counter from './counter'     import son from './son'
      // 2.在ccmponents里注册子组件    components : {
              counter,
              son
          },
      // 3.在template里使用子组件   <son></son>
           
       // 4.如果需要传递数据,也是在templete里写
       
         <counter :num="number"></counter>
    The sub-component only needs to do one thing
  • 1. Use props to accept data, and you can use the data directly
    • 2. The data received by the sub-component cannot be modified. If you really need to modify it, you can use calculated properties, or assign the data to a variable in the child component data

    •        

         // 1.用Props接受数据      props: [               'num'
                 ],
             
      // 2.如果需要修改得到的数据,可以这样写
         props: [            'num'
              ],  data () {        return {
                  number : this.num
              }
          },
      The child component passes data to the parent component

The parent component needs to do a total of 2 things

  • Define the event in the template
    • In Write functions in methods to listen to the event triggering of sub-components

    •        

      // 1. 在templete里应用子组件时,定义事件changeNumber
            <counter :num="number"                 @changeNumber="changeNumber"
            >
            </counter>
             
      // 2. 用changeNumber监听事件是否触发
              methods: {
                  changeNumber(e){                console.log('子组件emit了',e);                this.number = e
                  },
              }
    The sub-component needs a total of 1 thing
  • #After the data changes, use $emit to trigger it
    •      

      // 1. 子组件在数据变化后,用$emit触发即可,第二个参数可以传递参数
              methods: {
                  increment(){                    this.number++                    this.$emit('changeNumber', this.number)
                      },
              }
      The second communication method: eventBus
    eventBus communication This method is aimed at communication between non-parent and child components, and its principle is still through event triggering and monitoring.

But because they are non-parent-child components, they need an intermediate component to connect.

I use it by defining a component that can be accessed by all components on the root component, which is the #app component. The specific usage is as follows

Using eventBus to pass data, we have a total of Three things need to be done

1. Add the Bus attribute to the app component (so that all components can access it through this.$root.Bus, and there is no need to introduce any files)

  • 2. In component 1, this.$root.Bus.$emit triggers the event

  • 3. In component 2, this. $root.Bus.$on listening event

  •        
    // 1.在main.js里给app组件,添加bus属性import Vue from 'vue'new Vue({
      el: '#app',
      components: { App },  template: '<App/>',
      data(){    return {
          Bus : new Vue()
        }
      }
    })
             
    // 2.在组件1里,触发emitincrement(){
            this.number++
            this.$root.Bus.$emit('eventName', this.number)
        },
           
    // 3.在组件2里,监听事件,接受数据mounted(){    this.$root.Bus.$on('eventName', value => {        this.number = value
            console.log('busEvent');
        })
    },

    The third communication method: using localStorage or sessionStorage

  • This kind of communication is relatively simple, the disadvantage is that the data and The state is relatively chaotic and not easy to maintain.

Get data through window.localStorage.getItem(key)

Store data through window.localStorage.setItem(key, value)

Please use JSON.parse() / JSON.stringify () Convert data format.


The fourth communication method: using Vuex

Vuex is more complicated, you can write a separate article

Related recommendations:

Vue component development experience sharing

Detailed explanation of parent-child communication of vue components

Detailed explanation of dynamic loading of Vue component instances in the permission management module

The above is the detailed content of Sharing examples of 4 Vue component communication methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn