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

JavaScript Canvas draws dynamic wireframe effect

This article shares the specific code of JavaScri...

JavaScript to achieve simple drag effect

This article shares the specific code of JavaScri...

Summary of various common join table query examples in MySQL

This article uses examples to describe various co...

How to find the my.ini configuration file in MySQL 5.6 under Windows

Make a note so you can come back and check it lat...

Detailed explanation of MySQL joint query optimization mechanism

Table of contents MySQL federated query execution...

CSS specification BEM CSS and OOCSS sample code detailed explanation

Preface During project development, due to differ...

Use of vuex namespace

Table of contents Since Vuex uses a single state ...

Example of implementing colored progress bar animation using CSS3

Brief Tutorial This is a CSS3 color progress bar ...

A brief discussion on React Component life cycle functions

What are the lifecycle functions of React compone...

The principle and implementation of two-way binding in Vue2.x

Table of contents 1. Implementation process 2. Di...

Detailed explanation of the use of the clip-path property in CSS

Use of clip-path polygon The value is composed of...

jQuery to achieve sliding stairs effect

This article shares the specific code of jQuery t...

MySQL 8.0.12 installation configuration method and password change

This article records the installation and configu...

Interaction in web design: A brief discussion on paging issues

Function: Jump to the previous page or the next p...