Summary of twelve methods of Vue value transfer

Summary of twelve methods of Vue value transfer

1. From father to son

(1) Bind a property to the child component tag of the parent component and mount the variable to be transferred. (2) Accept data through props in the child component. Props can be an array or an object. The received data can be directly used props: ["property name"] props:{property name: data type}
Code example:

//Parent component <template>
  <div>
    <i>Parent component</i>
    <!--Page usage-->
    <son :data='name'></son> 
  </div>
</template>

<script>
import son from "./son.vue"; //Import parent component export default {
  components: { son }, //Register component name: "parent component",
  data() {
    return {
      name: "Frazier", //parent component defines variables};
  },
};
</script>
//Subcomponent <template>
  <div>{{data}}</div>
</template>

<script>
export default {
components: { },
  name: 'Subcomponent',
  props:["data"],
};
</script>

2. Son to Father

(1) Customize an event on the child component tag of the parent component and then call the required method.
(2) In the child component method, this.$emit("event") is used to trigger the event defined in the parent component, and the data is passed in the form of parameters.
Code example:

//Parent component <template>
  <div>
    <i>Parent component</i>
    <!--Page usage-->
    <son @lcclick="lcclick"></son>//Customize an event</div>
</template>

<script>
import son from "./son.vue"; //Import parent component export default {
  components: { son }, //Register component name: "parent component",
  data() {
    return {};
  },
  methods: {
    lcclick(){
      alert('son passes on to father')
    }
  },
};
</script>

//Subcomponent <template>
  <div>
    <button @click="lcalter">Click me</button>
  </div>
</template>

<script>
export default {
components: { },
  name: 'Subcomponent',
  methods: {
    lcalter(){
      this.$emit('lcclick')//Trigger the event through emit}
  },
};
</script>

3. Brother component communication (bus)

(1) Create a new Bus.js file in src and export an empty vue instance
(2) Introduce Bus.js on the data transmission side and then dispatch events through Bus. emit ("event name", "parameters"). Data is dispatched by emit ("event name", "parameters"), and data is transmitted in the form of parameters of emit().
(3) Introduce Bus.js on the side that receives the data and then use Bus.$on("event name", (data) => {data is the received data})

Image examples:

insert image description here

insert image description here

insert image description here

4. ref/refs (parent-child component communication)

(1) If ref is used on a normal DOM element, the reference points to the DOM element; if it is used on a child component, the reference points to the component instance.
(2) You can call component methods or access data directly through instances. It can also be regarded as a kind of value transfer from child component to parent component
Code example:

//Parent component <template>
  <div>
    <button @click="sayHello">sayHello</button>
    <child ref="childForRef"></child>
  </div>
</template>
<script>
import child from './child.vue'
  export default {
    components: { child },
    data () {
      return {
        childForRef: null,
      }
    },
    mounted() {
      this.childForRef = this.$refs.childForRef;
      console.log(this.childForRef.name);
    },
    methods: {
      sayHello() {
        this.childForRef.sayHello()
      }
    }
  }
</script>
//Subcomponent <template>
  <div>child's content</div>
</template>
<script>
export default {
  data () {
    return {
      name: 'I am a child',
    }
  },
  methods: {
    sayHello() {
      console.log('hello');
      alert('hello');
    }
  }
}
</script>

5. Vuex communication

Components dispatch to actions, which are asynchronous operations. Actions commit to mutations, which change the state through logical operations, thereby synchronizing to components and updating their data status.
Code example:

//parent component template>
  <div id="app">
    <ChildA/>
    <ChildB/>
  </div>
</template>
<script>
  import ChildA from './ChildA' // Import component A import ChildB from './ChildB' // Import component B export default {
    components: {ChildA, ChildB} // Register components}
</script>
//Subcomponent A
<template>
 <div id="childA">
   <h1>I am component A</h1>
   <button @click="transform">Click me to let component B receive data</button>
   <p>Because B was clicked, the message changed: {{BMessage}}</p>
 </div>
</template>
<script>
 export default {
   data() {
     return {
       AMessage: 'Hello, component B, I am component A'
     }
   },
   computed: {
     BMessage() {
       // Store the data of component B obtained from the store here return this.$store.state.BMsg
     }
   },
   methods: {
     transform() {
       // Trigger receiveAMsg and store the data of component A in the store this.$store.commit('receiveAMsg', {
         AMsg: this.AMessage
       })
     }
   }
 }
</script>
//Subcomponent B
<template>
 <div id="childB">
   <h1>I am component B</h1>
   <button @click="transform">Click me to let component A receive data</button>
   <p>Click A, my message changes: {{AMessage}}</p>
 </div>
</template>

<script>
 export default {
   data() {
     return {
       BMessage: 'Hello, component A, I am component B'
     }
   },
   computed: {
     AMessage() {
       // Here we store the data of component A obtained from the store return this.$store.state.AMsg
     }
   },
   methods: {
     transform() {
       // Trigger receiveBMsg and store the data of component B in the store this.$store.commit('receiveBMsg', {
         BMsg: this.BMessage
       })
     }
   }
 }
</script>

//vuex
import Vue from 'vue'
 import Vuex from 'vuex'
 Vue.use(Vuex)
 const state = {
   AMsg: '',
   BMsg: ''
 }
 
 const mutations = {
   receiveAMsg(state, payload) {
     // Store the data of component A in state
     state.AMsg = payload.AMsg
   },
   receiveBMsg(state, payload) {
     // Store the data of component B in state
     state.BMsg = payload.BMsg
   }
 }
 
 export default new Vuex.Store({
   state,
   mutations
 })

6. $parent

Parent can be used to obtain the parent component instance, and then the properties and methods of the parent component can be accessed through this instance. It also has a brother parent that can obtain the parent component instance, and then the properties and methods of the parent component can be accessed through this instance. It also has a brother parent that can obtain the parent component instance, and then the properties and methods of the parent component can be accessed through this instance. It also has a brother root that can obtain the root component instance.
Code example:

// Get the parent component's data this.$parent.foo

// Write data to the parent component this.$parent.foo = 2

// Access the parent component's computed property this.$parent.bar

//Call the parent component method this.$parent.baz()

//In the example of passing a child component to a parent component, you can use this.$parent.getNum(100) to pass the value to the parent component.

7.sessionStorage value transfer

SessionStorage is a global object of the browser, and the data stored in it will be cleared when the page is closed. Using this feature, we can share a copy of data across all pages.
Code example:

// Save data to sessionStorage
sessionStorage.setItem('key', 'value');

// Get data from sessionStorage let data = sessionStorage.getItem('key');

// Delete saved data from sessionStorage sessionStorage.removeItem('key');

// Delete all saved data from sessionStorage sessionStorage.clear();

Note: What is stored in it is key-value pairs, which can only be string types. If you want to store objects, you need to use let objStr = JSON.stringify(obj) to convert it into a string and then store it (when using let obj = JSON.parse(objStr) to parse it into an object).
I recommend a library called good-storage, which encapsulates sessionStorage and allows you to directly use its API to store objects.

//localStorage
 storage.set(key,val) 
 storage.get(key, def)
//sessionStorage
 storage.session.set(key, val)
 storage.session.get(key, val)

8. Routing value

Use question mark to pass value
When page A jumps to page B, use this. router . push ( ' / B ? name = danseek ' ) Page B can use this . router.push('/B?name=danseek') Page B can use this. router.push('/B?name=danseek') Page B can use this.route.query.name to get the value passed from page A. Pay attention to the difference between router and route above.
Use colon to pass value <br /> Configure the following route:

{
    path: '/b/:name',
    name: 'b',
    component: () => import( '../views/B.vue')
 },

On page B, you can use this.$route.params.name to get the value of name passed in by the route

Use parent-child component to pass value Since router-view itself is also a component, we can also use parent-child component to pass value, and then add props to the corresponding child page. Because the route is not refreshed after the type is updated, the latest type value cannot be directly obtained in the mounted hook of the child page, but watch is used

<router-view :type="type"></router-view>

// Subpage props: ['type']
watch:
       type(){
           // console.log("In this method, you can always get the latest data: type=", this.type)
       },
},

9. Ancestor's grandchild $attrs

Under normal circumstances, you need to use the props of the father as an intermediate transition, but in this way, the father component will have more attributes that are not related to the business of the parent component, and the coupling is high. With the help of $attrs, it can be simplified, and neither the grandparent nor the grandchild does not need to be modified.
Ancestor component:

<template>
    <section>
        <parent name="grandParent" sex="男" age="88" hobby="code" @sayKnow="sayKnow"></parent>
    </section>
</template>

<script>
    import Parent from './Parent'
    export default {
        name: "GrandParent",
        components:
          Parent
        },
        data() {
            return {}
        },
        methods: {
          sayKnow(val){
            console.log(val)
          }
        },
        mounted() {
        }
    }
</script>

Parent Component

<template>
  <section>
    <p>The parent component receives</p>
    <p>Grandfather's name: {{name}}</p>
    <children v-bind="$attrs" v-on="$listeners"></children>
  </section>
</template>

<script>
  import Children from './Children'

  export default {
    name: "Parent",
    components:
      Children
    },
    // The parent component receives the name, so the name value will not be passed to the child component's props:['name'],
    data() {
      return {}
    },
    methods: {},
    mounted() {
    }
  }
</script>

Subcomponents

<template>
  <section>
    <p>Subcomponent received</p>
    <p>Grandfather's name: {{name}}</p>
    <p>Grandfather's gender: {{sex}}</p>
    <p>Grandfather's age: {{age}}</p>
    <p>Grandfather's hobby: {{hobby}}</p>

    <button @click="sayKnow">I know</button>
  </section>
</template>

<script>
  export default {
    name: "Children",
    components: {},
    // Since the parent component has received the name attribute, name will not be passed to the child component props:['sex','age','hobby','name'],
    data() {
      return {}
    },
    methods: {
      sayKnow(){
        this.$emit('sayKnow','I know')
      }
    },
    mounted() {
    }
  }
</script>

10. Sun Chuanzu uses $listeners

Same as the ninth one

Ancestor Components

<template>
  <div id="app">
    <children-one @eventOne="eventOne"></children-one>
    {{ msg }}
  </div>
</template>
<script>
import ChildrenOne from '../src/components/children.vue'
export default {
  name: 'App',
  components:
    ChildrenOne,
  },
  data() {
    return {
      msg: ''
    }
  },
  methods: {
    eventOne(value) {
      this.msg = value
    }
  }
}
</script>

Parent Component

<template>
  <div>
    <children-two v-on="$listeners"></children-two>
  </div>
</template>

<script>
import ChildrenTwo from './childrenTwo.vue'

export default {
  name: 'childrenOne',
  components:
    ChildrenTwo
  }
}
</script>

Subcomponents

<template>
  <div>
    <button @click="setMsg">Click to pass to grandfather</button>
  </div>
</template>

<script>
export default {
  name: 'children',
  methods: {
    setMsg() {
      this.$emit('eventOne', '123')
    }
  }
}
</script>

11. Promise parameter passing

How to pass multiple parameters in promise resolve

//Similar to this usage, but in fact the last two parameters cannot be obtained promise = new Promise((resolve,reject)=>{
    let a = 1
    let b = 2
    let c = 3
    resolve(a,b,c) 
})
promise.then((a,b,c)=>{
    console.log(a,b,c)
})

resolve() can only accept and process one parameter, and any extra parameters will be ignored.
If you want multiple, use an array or object. .
Arrays

promise = new Promise((resolve,reject)=>{
    resolve([1,2,3]) 
})
promise.then((arr)=>{
    console.log(arr[0],arr[1],arr[2])
})

Object

promise = new Promise((resolve,reject)=>{
    resolve({a:1,b:2,c:3}) 
})
promise.then(obj=>{
    console.log(obj.a,obj.b,obj.c)
})

12. Global variables

Define a global variable, assign a value directly to the component with a value, and use it directly in the required component. For details, please refer to my blog.
Just click on the blog link Global variables

This concludes this article on the twelve methods of Vue value transfer. For more information on Vue value transfer, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Several value transfer methods in Vue (3 types)
  • Detailed explanation of how Vue components transfer values ​​to each other
  • Solution to Vue data assignment problem
  • Value passing and assignment issues in Vue

<<:  Detailed explanation of system input and output management in Linux

>>:  Detailed tutorial on installing MySQL 5.7.20 on RedHat 6.5/CentOS 6.5

Recommend

Let's talk in detail about the props attributes of components in Vue

Table of contents Question 1: How are props used ...

XHTML Getting Started Tutorial: Form Tags

<br />Forms are an important channel for use...

Introduction to the use of base link tag base

<br />When you click the link, the web page ...

Navicat remote connection to MySQL implementation steps analysis

Preface I believe that everyone has been developi...

I have compiled a few cool design sites that I think are good.

You must have inspiration to design a website. Goo...

Overview of MySQL Statistics

MySQL executes SQL through the process of SQL par...

MySQL 5.7.13 installation and configuration method graphic tutorial on Mac

MySQL 5.7.13 installation tutorial for Mac, very ...

CSS--overflow:hidden in project examples

Here are some examples of how I use this property ...

Teach you how to use webpack to package and compile TypeScript code

TypeScript Bundling webpack integration Usually, ...

How to install and configure Redis in CentOS7

Introduction There is no need to introduce Redis ...

Detailed explanation of CentOS configuration of Nginx official Yum source

I have been using the CentOS purchased by Alibaba...

Hexadecimal color codes (full)

Red and pink, and their hexadecimal codes. #99003...

CSS to achieve floating customer service effect

<div class="sideBar"> <div>...