Home > Web Front-end > Vue.js > body text

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

醉折花枝作酒筹
Release: 2023-01-13 00:45:18
Original
13624 people have browsed it

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(&#39;child&#39;,{    data(){      return {        mymessage:this.message      }    },    template:`      <div>        <input type="text" v-model="mymessage" @input="passData(mymessage)"> </div>    `,    props:[&#39;message&#39;],//设置props属性值,得到父组件传递过来的数据    methods:{      passData(val){        //触发父组件中的事件,向父组件传值        this.$emit(&#39;getChildData&#39;,val)      }    }  })  Vue.component(&#39;parent&#39;,{    template:`      <div>        <p>this is parent compoent!</p>        <child :message="message" v-on:getChildData="getChildData"></child>      </div>    `,    data(){      return {        message:&#39;hello&#39;      }    },    methods:{      //执行子组件触发的事件      getChildData(val){        console.log(val)      }    }  })
Copy after login
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(&#39;C&#39;,{
    template:`
      <div>
        <input type="text" v-model="$attrs.messagec" @input="passCData($attrs.messagec)"> </div>
    `,
    methods:{
      passCData(val){
        //触发父组件A中的事件
        this.$emit(&#39;getCData&#39;,val)
      }
    }
  })
  Vue.component(&#39;B&#39;,{
    data(){
      return {
        mymessage:this.message
      }
    },
    template:`
      <div>
        <input type="text" v-model="mymessage" @input="passData(mymessage)">
        <!-- C组件中能直接触发getCData的原因在于 B组件调用C组件时 使用 v-on 绑定了$listeners 属性 -->
        <!-- 通过v-bind 绑定$attrs属性,C组件可以直接获取到A组件中传递下来的props(除了B组件中props声明的) -->
        <C v-bind="$attrs" v-on="$listeners"></C>
      </div>
    `,
    props:[&#39;message&#39;],//得到父组件传递过来的数据
    methods:{
      passData(val){
        //触发父组件中的事件
        this.$emit(&#39;getChildData&#39;,val)
      }
    }
  })
  Vue.component(&#39;A&#39;,{
    template:`
      <div>
        <p>this is parent compoent!</p>
        <B :messagec="messagec" :message="message" v-on:getCData="getCData" v-on:getChildData="getChildData(message)"></B>
      </div>
    `,
    data(){
      return {
        message:&#39;hello&#39;,
        messagec:&#39;hello c&#39; //传递给c组件的数据
      }
    },
    methods:{
      getChildData(val){
        console.log(&#39;这是来自B组件的数据&#39;)
      },
      //执行C子组件触发的事件
      getCData(val){
        console.log("这是来自C组件的数据:"+val)
      }
    }
  })
Copy after login

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(&#39;brother1&#39;,{
    data(){      return {
        mymessage:&#39;hello brother1&#39;
      }
    },
    template:`      <p>
        <p>this is brother1 compoent!</p>
        <input type="text" v-model="mymessage" @input="passData(mymessage)">
      </p>    `,
    methods:{
      passData(val){        //触发全局事件globalEvent
        bus.$emit(&#39;globalEvent&#39;,val)
      }
    }
  })
  Vue.component(&#39;brother2&#39;,{
    template:`      <p>
        <p>this is brother2 compoent!</p>
        <p>brother1传递过来的数据:{{brothermessage}}</p>
      </p>    `,
    data(){      return {
        mymessage:&#39;hello brother2&#39;,
        brothermessage:&#39;&#39;
      }
    },
    mounted(){      //绑定全局事件globalEvent
      bus.$on(&#39;globalEvent&#39;,(val)=>{        this.brothermessage=val;
      })
    }
  })  //中央事件总线
  var bus=new Vue();  var app=new Vue({
    el:&#39;#app&#39;,
    template:`      <p>
        <brother1></brother1>
        <brother2></brother2>
      </p>    `
  })
Copy after login

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(&#39;child&#39;,{
    inject:[&#39;for&#39;],//得到父组件传递过来的数据
    data(){
      return {
        mymessage:this.for
      }
    },
    template:`})
  Vue.component(&#39;parent&#39;,{
    template:`this is parent compoent!`,
    provide:{
      for:&#39;test&#39;
    },
    data(){
      return {
        message:&#39;hello&#39;
      }
    }
  })
Copy after login

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(&#39;child&#39;,{
    props:{
      value:String, //v-model会自动传递一个字段为value的prop属性    },
    data(){      return {
        mymessage:this.value
      }
    },
    methods:{
      changeValue(){        this.$emit(&#39;input&#39;,this.mymessage);//通过如此调用可以改变父组件上v-model绑定的值      }
    },
    template:`      <p>
        <input type="text" v-model="mymessage" @change="changeValue">
      </p>  })
  Vue.component(&#39;parent&#39;,{
    template:`      <p>
        <p>this is parent compoent!</p>
        <p>{{message}}</p>
        <child v-model="message"></child>
      </p>    `,
    data(){      return {
        message:&#39;hello&#39;
      }
    }
  })  var app=new Vue({
    el:&#39;#app&#39;,
    template:`      <p>
        <parent></parent>
      </p>    `
  })
Copy after login

$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(&#39;child&#39;,{
    props:{
      value:String, //v-model会自动传递一个字段为value的prop属性    },
    data(){      return {
        mymessage:this.value
      }
    },
    methods:{
      changeValue(){        this.$parent.message = this.mymessage;//通过如此调用可以改变父组件的值      }
    },
    template:`      <p>
        <input type="text" v-model="mymessage" @change="changeValue">
      </p>  })
  Vue.component(&#39;parent&#39;,{
    template:`      <p>
        <p>this is parent compoent!</p>
        <button @click="changeChildValue">test</button >
        <child></child>
      </p>    `,
    methods:{
      changeChildValue(){        this.$children[0].mymessage = &#39;hello&#39;;
      }
    },
    data(){      return {
        message:&#39;hello&#39;
      }
    }
  })  var app=new Vue({
    el:&#39;#app&#39;,
    template:`      <p>
        <parent></parent>
      </p>    `
  })
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!