Detailed explanation of Vue's seven value transfer methods

Detailed explanation of Vue's seven value transfer methods

1. From father to son

Define the props field in the child component, and the type is array (if you need to limit the field value type, you can also define it in the form of an object). As shown in the example below, the parent component mounts the child component HelloWorld , assigns a value title on the component tag, and the child component HelloWorld defines props , which contains a value called title , so that the child component can use the value of the parent component.

Parent Component

<template>
 <div>
 <HelloWorld :title="msg" />
 </div>
</template>

<script>
import HelloWorld from "../components/HelloWorld.vue";

export default {
 name: "Home",
 data() {
 return {
  msg: "Search Music",
 };
 },
 components:
 HelloWorld,
 },
};
</script>

Subcomponents

<template>
 <div class="hello">
 <h1>{{ title }}</h1>
 </div>
</template>

<script>
export default {
 name: "HelloWorld",
 props:["title"],
 data() {
 return {};
 },
};
</script>

2. Son to Father

To pass a value from child to parent, you need to trigger an event in the child component. In the event, call $emit('父組件的方法名', '傳遞的值') , and then receive the passed value in the parent component through a custom event.

Subcomponents

<template>
 <div class="hello">
 <h1 @click="add">{{ title }}</h1>
 </div>
</template>

<script>
export default {
 name: "HelloWorld",
 props: ["title"],
 data() {
 return {
  age:18
 };
 },
 methods: {
 add(){
  this.$emit("childEvent", this.age);
 }
 },
};
</script>

Parent Component

<template>
 <div>
 <HelloWorld @childEvent="parentEvent" :title="msg" />
 </div>
</template>

<script>
import HelloWorld from "../components/HelloWorld.vue";

export default {
 name: "Home",
 data() {
 return {
  msg: "Search Music",
 };
 },

 methods: {
 parentEvent(e) {
  console.log(e);
 },
 },
 components:
 HelloWorld,
 },
};
</script>

3. Brother component value transfer

1. First create a bus.js file, new a Vue instance in bus.js to act as the middle layer for transmitting data.

import Vue from 'vue';
export default new Vue;

2. Introduce bus.js into component A and pass parameters through bus.$emit('事件名','參數')

<template>
 <div class="hello">
 <h1 @click="add">{{ title }}</h1>
 </div>
</template>

<script>
import bus from "../publicFn/bus.js";

export default {
 name: "HelloWorld",
 props: ["title"],
 data() {
 return {
  age:18
 };
 },
 methods: {
 add(){
  bus.$emit("childEvent", this.age);
 }
 },
};
</script>

3. Use $on('事件名', function(){}) to receive in the mounted cycle of component B

<template>
 <div id='swiper'>
 <button>I am a button</button>
 </div>
</template>

<script>

import bus from "../publicFn/bus.js";

export default {
 name:'Swiper',
 data (){
 return {

 }
 },
 mounted(){
 bus.$on("childEvent", (e) => {
  console.log(e)
 })
 }
}
</script>

4. Parent components use data and methods of child components

1. Write the ref attribute on the subcomponent tag

2. The parent component can access the child component through this.$refs.id.方法名or this.$refs.id.屬性名.

Parent Component

<template>
 <div>
 <HelloWorld :title="msg" ref="hello" />
 <button @click="parentEvent">I am a father</button>
 </div>
</template>

<script>
import HelloWorld from "../components/HelloWorld.vue";

export default {
 name: "Home",
 data() {
 return {
  msg: "Search Music",
 };
 },

 methods: {
 parentEvent() {
  this.$refs.hello.add();
  console.log(this.$refs.hello.age);
 },
 },
 components:
 HelloWorld
 },
};
</script>

Subcomponents

<template>
 <div class="hello">
 <h1>{{ title }}</h1>
 </div>
</template>

<script>
export default {
 name: "HelloWorld",
 props: ["title"],
 data() {
 return {
  age:18
 };
 },
 methods: {
 add(){
  console.log("I am a child component");
 }
 },
};
</script>

5. Child components use the data and methods of parent components

In a child component, you can use $parent to access the data and methods of its parent component. If it is multi-nested, you can also use multiple layers of $parent .

Parent Component

<template>
 <div>
 <HelloWorld :title="msg" ref="hello" />
 </div>
</template>

<script>
import HelloWorld from "../components/HelloWorld.vue";

export default {
 name: "Home",
 data() {
 return {
  msg: "Search Music",
 };
 },

 methods: {
 parentEvent() {
  console.log("I am the method of the parent component");
 },
 },
 components:
 HelloWorld
 },
};
</script>

Subcomponents

<template>
 <div class="hello">
 <h1 @click="add">{{ title }}</h1>
 </div>
</template>

<script>
export default {
 name: "HelloWorld",
 props: ["title"],
 data() {
 return {
  age:18
 };
 },
 methods: {
 add(){
  console.log(this.$parent.msg)
  this.$parent.parentEvent();
 }
 },
};
</script>

6. Vuex value transfer

Vuex is a state management pattern developed specifically for Vue.js applications. It uses centralized storage to manage the status of all components of an application and uses corresponding rules to ensure that the status changes in a predictable manner. Generally, it is not needed for small projects.

6.1, define the store

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
 state: {
 school: "Tsinghua University",
 a:"nice"
 },
 getters: {
 returnVal(state) {
  return state.school + state.a;
 },
 },
 mutations:
 changeSchool(state, val) {
  state.school = val;
  console.log('Modification successful');
 },
 },
 actions: {},
 modules: {}
});

6.2, Mount

import Vue from 'vue';
import App from './App.vue';
import router from "./router";
import store from "./store";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import publicFn from "./publicFn/publicFn";

Vue.config.productionTip = false


const url = process.env.VUE_APP_URL;
Vue.prototype.$url = url;
Vue.prototype.$publicFn = publicFn;

Vue.use(ElementUI);

new Vue({
 router,
 store,
 render: h => h(App),
}).$mount('#app')

6.3, Use

<template>
 <div class="hello">
 <h1 @click="add">{{ title }}</h1>
 </div>
</template>

<script>
export default {
 name: "HelloWorld",
 props: ["title"],
 data() {
 return {
  age:18
 };
 },
 methods: {
 add(){
  console.log(this.$store.state.school);//Get the value//this.$store.commit('changeSchool', 'Peking University');//Modify the value// console.log(this.$store.getters.returnVal)//Get the filtered value}
 },
};
</script>

7. Routing value

7.1 Passing values ​​through query

Note: This method will not lose the page refresh parameters, and will display the parameters after the address bar, http://localhost:9000/#/conter?id=10086&name=%E9%B9%8F%E5%A4%9A%E5%A4%9A

Page A

<template>
 <div>
 <HelloWorld :title="msg" ref="hello" />
 <button @click="parentEvent">Jump</button>
 </div>
</template>

<script>
import HelloWorld from "../components/HelloWorld.vue";

export default {
 name: "Home",
 data() {
 return {
  msg: "Search Music",
 };
 },

 methods: {
 parentEvent() {
  this.$router.push({
  path:"/conter",
  name:'conter',
  query:{
   id:10086,
   name:"Peng Duoduo"
  }
  })
 },
 },
 components:
 HelloWorld
 },
};
</script>

Page B

<template>
 <div id='conter'>

 </div>
</template>

<script>

export default {
 name:'conter',
 data (){
 return {

 }
 },
 created (){
 console.log(this.$route.query.id, this.$route.query.name);
 },
}
</script>

7.2 Passing values ​​via params

Note: When refreshing the page in this way, the parameters will be lost, but they can be received and stored in sessionStorage .

A-page

<template>
 <div>
 <HelloWorld :title="msg" ref="hello" />
 <button @click="parentEvent">Jump</button>
 </div>
</template>

<script>
import HelloWorld from "../components/HelloWorld.vue";

export default {
 name: "Home",
 data() {
 return {
  msg: "Search Music",
 };
 },

 methods: {
 parentEvent() {
  this.$router.push({
  path:"/conter",
  name:"conter",
  params:{
   id:10086,
   name:"Peng Duoduo"
  }
  })
 },
 },
 components:
 HelloWorld
 },
};
</script>

Page B

<template>
 <div id='conter'>

 </div>
</template>

<script>

export default {
 name:'conter',
 data (){
 return {

 }
 },
 created (){
 console.log(this.$route.params.id, this.$route.params.name);
 },
}
</script>

This concludes this article about Vue's seven value-transferring methods. For more information about Vue's value-transferring methods, please search 123WORDPRESS.COM's previous articles or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A brief discussion on Vue3 father-son value transfer
  • Detailed explanation of Vue parent-child component value transfer and one-way data flow issues
  • Vue parent-child component mutual value transfer and call
  • Some pitfalls of Vue parent-child component value transfer
  • Example of passing values ​​between vue child components and parent components
  • Vue father-son value transfer, brother value transfer, child-father value transfer detailed explanation

<<:  Install OpenSSH on Windows and log in to the Linux server by generating an SSH key

>>:  Detailed explanation of the basic usage of SSH's ssh-keygen command

Recommend

Centos builds chrony time synchronization server process diagram

My environment: 3 centos7.5 1804 master 192.168.1...

Detailed explanation of JS browser storage

Table of contents introduction Cookie What are Co...

Each time Docker starts a container, the IP and hosts specified operations

Preface Every time you use Docker to start a Hado...

MySQL Interview Questions: How to Set Up Hash Indexes

In addition to B-Tree indexes, MySQL also provide...

How to implement interception of URI in nginx location

illustrate: Root and alias in location The root d...

Solution to Vue data assignment problem

Let me summarize a problem that I have encountere...

Implementation of scheduled backup in Mysql5.7

1. Find mysqldump.exe in the MySQL installation p...

Example code for implementing image adaptive container with CSS

There is often a scenario where the image needs t...

Using Nginx to implement grayscale release

Grayscale release refers to a release method that...

How to understand Vue's simple state management store mode

Table of contents Overview 1. Define store.js 2. ...

HTML+CSS to achieve charging water drop fusion special effects code

Table of contents Preface: accomplish: Summarize:...

The grid is your layout plan for the page

<br /> English original: http://desktoppub.a...