Home  >  Article  >  Web Front-end  >  What are the 8 ways to pass values ​​in vue

What are the 8 ways to pass values ​​in vue

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-04-27 17:35:0713534browse

The value-passing methods include: props and "$emit", "$attrs" and "$listeners", central event bus, v-model, provide and inject, "$parent" and "$children", vuex, localStorage/session.

What are the 8 ways to pass values ​​in vue

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

For vue, messaging between components is very important. The following is my summary of common ways of messaging between components.

  • props and $emit (commonly used)

  • $attrs and $listeners

  • Central event Bus (non-parent-child inter-component communication)

  • v-model

  • ##provide and inject

  • $parent and $children

  • vuex


##props and $emit

The parent component passes data to the child component through prop, and the child component passes data to the parent component through $emit triggering the event.

Vue.component('child',{    data(){      return {        mymessage:this.message      }    },    template:`      
`, props:['message'],//设置props属性值,得到父组件传递过来的数据 methods:{ passData(val){ //触发父组件中的事件,向父组件传值 this.$emit('getChildData',val) } } }) Vue.component('parent',{ template:`

this is parent compoent!

`, data(){ return { message:'hello' } }, methods:{ //执行子组件触发的事件 getChildData(val){ console.log(val) } } })
In the above example, there are parent component parent and child component child.


    The parent component passes the message data to the child component, and binds a getChildData event through v-on to listen for the trigger event of the child component;
  • The subcomponent gets the relevant message data through props, and finally triggers the getChildData event through this.$emit
  • ##$attrs and $listeners

The first way to handle data transmission between parent and child components has a problem: if there is child component B under parent component A, and there is component C under component B, what if component A wants to pass data to component C? What to do? If we adopt the first method, we must let component A pass the message to component B through prop, and component B passes the message to component C through prop; if there are more components between component A and component C, then use this method It's very complicated. Vue 2.4 has provided $attrs and $listeners to solve this problem, allowing components A to pass messages to component C.

Vue.component('C',{
    template:`
      dc6dce4a544fdca2df29d5ac0ea9906b
        7d642c02fff9fdf1e7a3b0ccd8651dae 16b28748ea4df4d9c2150843fecfba68
    `,
    methods:{
      passCData(val){
        //触发父组件A中的事件
        this.$emit('getCData',val)
      }
    }
  })
  Vue.component('B',{
    data(){
      return {
        mymessage:this.message
      }
    },
    template:`
      dc6dce4a544fdca2df29d5ac0ea9906b
        7fd7f75d01cda5f402cb25a0a7de995b
        086635eb7aaa93b3bc42be25ba16f2cd
        d4ef16d70a197139b9a0445162e00bb6
        2b4f3405cb593d7dabb61895b5e4f0275f6acab10c476fc264ba16ac4aa7415c
      16b28748ea4df4d9c2150843fecfba68
    `,
    props:['message'],//得到父组件传递过来的数据
    methods:{
      passData(val){
        //触发父组件中的事件
        this.$emit('getChildData',val)
      }
    }
  })
  Vue.component('A',{
    template:`
      dc6dce4a544fdca2df29d5ac0ea9906b
        e388a4556c0f65e1904146cc1a846beethis is parent compoent!94b3e26ee717c64999d7867364b1b4a3
        e2af931dfa4ed32474136138c8cc6ea341908b66e4bc50a75b443e0dfafd01f9
      16b28748ea4df4d9c2150843fecfba68
    `,
    data(){
      return {
        message:'hello',
        messagec:'hello c' //传递给c组件的数据
      }
    },
    methods:{
      getChildData(val){
        console.log('这是来自B组件的数据')
      },
      //执行C子组件触发的事件
      getCData(val){
        console.log("这是来自C组件的数据:"+val)
      }
    }
  })

Central Event Bus

The above two methods deal with data transfer between parent and child components. What if the two components are not in a parent-child relationship? ? In this case, a central event bus can be used. Create a new Vue event bus object, then trigger the event through bus.$emit, and bus.$on listens for the triggered event.

Vue.component('brother1',{
    data(){      return {
        mymessage:'hello brother1'
      }
    },
    template:`      e388a4556c0f65e1904146cc1a846bee
        e388a4556c0f65e1904146cc1a846beethis is brother1 compoent!94b3e26ee717c64999d7867364b1b4a3
        7fd7f75d01cda5f402cb25a0a7de995b
      94b3e26ee717c64999d7867364b1b4a3    `,
    methods:{
      passData(val){        //触发全局事件globalEvent
        bus.$emit('globalEvent',val)
      }
    }
  })
  Vue.component('brother2',{
    template:`      e388a4556c0f65e1904146cc1a846bee
        e388a4556c0f65e1904146cc1a846beethis is brother2 compoent!94b3e26ee717c64999d7867364b1b4a3
        e388a4556c0f65e1904146cc1a846beebrother1传递过来的数据:{{brothermessage}}94b3e26ee717c64999d7867364b1b4a3
      94b3e26ee717c64999d7867364b1b4a3    `,
    data(){      return {
        mymessage:'hello brother2',
        brothermessage:''
      }
    },
    mounted(){      //绑定全局事件globalEvent
      bus.$on('globalEvent',(val)=>{        this.brothermessage=val;
      })
    }
  })  //中央事件总线
  var bus=new Vue();  var app=new Vue({
    el:'#app',
    template:`      e388a4556c0f65e1904146cc1a846bee
        db8e0981216ffea9e11695fcc5f3d159422ba0722828b812771cb3535114ead2
        16c7ea7f21a2f1d37ba1ce836c6f09ccd9f59e38b643491a2fad5c23f0d6a95e
      94b3e26ee717c64999d7867364b1b4a3    `
  })

provide and inject

were added in the

2.2.0

version of Vue.js provide and inject options. They appear in pairs and are used to pass data down from the parent component. Provide variables through provider in the parent component, and then inject variables through inject in the child component. No matter how deep the subcomponent is, as long as inject is called, the data in the provider can be injected. Instead of being limited to obtaining data only from the prop attribute of the current parent component, child components can call it as long as it is within the life cycle of the parent component.

Vue.component('child',{
    inject:['for'],//得到父组件传递过来的数据
    data(){
      return {
        mymessage:this.for
      }
    },
    template:`})
  Vue.component('parent',{
    template:`this is parent compoent!`,
    provide:{
      for:'test'
    },
    data(){
      return {
        message:'hello'
      }
    }
  })

v-model

When the parent component passes the value to the child component through v-model, it will automatically pass a value prop attribute, and pass this in the child component .$emit('input',val) automatically modifies the value of v-model binding

Vue.component('child',{
    props:{
      value:String, //v-model会自动传递一个字段为value的prop属性    },
    data(){      return {
        mymessage:this.value
      }
    },
    methods:{
      changeValue(){        this.$emit('input',this.mymessage);//通过如此调用可以改变父组件上v-model绑定的值      }
    },
    template:`      e388a4556c0f65e1904146cc1a846bee
        6708e6166751e70f627e757fbdf53cce
      94b3e26ee717c64999d7867364b1b4a3  })
  Vue.component('parent',{
    template:`      e388a4556c0f65e1904146cc1a846bee
        e388a4556c0f65e1904146cc1a846beethis is parent compoent!94b3e26ee717c64999d7867364b1b4a3
        e388a4556c0f65e1904146cc1a846bee{{message}}94b3e26ee717c64999d7867364b1b4a3
        2683ad86c93f2ee4c92e7d9b5d7c94a27d4dd9c7239aac360e401efe89cbb393
      94b3e26ee717c64999d7867364b1b4a3    `,
    data(){      return {
        message:'hello'
      }
    }
  })  var app=new Vue({
    el:'#app',
    template:`      e388a4556c0f65e1904146cc1a846bee
        58652436a08d62d32b90566dafe0913cdb7b8d074c72824ed121864240fe4c81
      94b3e26ee717c64999d7867364b1b4a3    `
  })

$parent and $children

can be done inside the component Directly operate the parent component through the child component $parent, and the parent component operates the child component through $children.

Vue.component('child',{
    props:{
      value:String, //v-model会自动传递一个字段为value的prop属性    },
    data(){      return {
        mymessage:this.value
      }
    },
    methods:{
      changeValue(){        this.$parent.message = this.mymessage;//通过如此调用可以改变父组件的值      }
    },
    template:`      

}) Vue.component('parent',{ template:`

this is parent compoent!

`, methods:{ changeChildValue(){ this.$children[0].mymessage = 'hello'; } }, data(){ return { message:'hello' } } }) var app=new Vue({ el:'#app', template:`

` })

vuex handles data interaction between components

If the business logic is complex and many components need to process some public data at the same time, the above methods may not be conducive to the maintenance of the project. Vuex’s approach is to extract these public data, and then Other components can read and write this common data, thus achieving the purpose of decoupling.

localStorage / sessionStorage

This kind of communication is relatively simple. The disadvantage is that the data and status are confusing and not easy to maintain.

Get data through

window.localStorage.getItem(key)

Get data

Pass window.localStorage.setItem(key,value)

Storage data

Pay attention to using JSON.parse() / JSON.stringify() for data format conversion

localStorage / sessionStorage can be combined with vuex to achieve persistent data storage, and use vuex to solve the problem of data and status confusion.

[Related recommendations: "

vue.js Tutorial

"]

The above is the detailed content of What are the 8 ways to pass values ​​in vue. 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