For vue, messaging between components is very important. Here is my summary of common methods of messaging between components.
1. Props Parent component--->Child component communication
Parent component---properties pass values to child components
Subcomponents----receive data in props
<Son :datas="fData"></Son> <script> import Son from '@/components/son' export default{ name:'Father', components:{Son}, data(){ return{ fData:'I am the value passed to the child component -props way' } } } </script>
The parameter name accepted by child component props should be consistent with the attribute name defined when passed by the parent component.
<template> <div>I'm the parent component's data:{{fData}}</div> <div @click=changeData>I am the parent component passing modified data:{{mydata}}</div> </template> <script> export default{ name:'Son', props:{ fData:{ type:String, default:'' } } data(){ mydata: }, methods:{ changeData(){ += 'Change data' } }, } </script>
Notice:
- Children components cannot directly modify the value passed by the parent component: because of Vue's one-way data flow mechanism, if the parent component's value is directly modified, it will be "contaminated". (props are one-way bound (read-only attribute): When the property of the parent component changes, it will be transmitted to the child component, but will not in turn)
The error message is probably: Vue uses prop to communicate with error: Avoid mutating a prop directly since the value will be overwritten whenever the parent - Solution: You can define a variable mydata in the child component to receive fData data
- If the parameter passing type is not sure, you can write this:
props:{ fData:{ type:[String,Number], default:'' } }
2. $emit child component--->parent component pass
- Subcomponent binding custom events
- The first parameter of $emit() is: the custom event name, and the second parameter is: the data to be passed
- Use $emit() to trigger data change
Subcomponents
<el-button @click="handleEmit">Change parent component</el-button> <script> export default{ name:'Son', methods:{ handleEmit(){ this.$emit('triggerEmit','Subcomponent data') } } } </script>
Parent component (the event name sent by the child component must be consistent with the event name accepted by the parent component)
<Son @triggerEmit="changeData"></Son> <script> import Son from '@/components/son' export default{ name:'Father', components:{Son}, methods:{ changeData(name){ (name) // => I'm data from a child component } } } </script>
$emit and props are combined with brother components to pass values
- Parent component introduces two child components
- The parent component acts as a bridge
Parent component
<childA :myName="name"></ChildA> <ChildB :myName="name" @changeName="editName"></ChildB> export default{ data() { return { name: 'Hello data' } }, methods: { editName(name){ = name } } }
Subcomponent B changes to receive data
<p>Name: {{ myName }}</p>
<button @click="changeName">Modify your name</button> <script> export default{ props: { myName:String }, methods: { changeName() { this.$emit('changeName', 'New Data Name') } } } </script>
Subcomponent A receives data
<p>Name:{{ newName }}</p> <script> export default{ props: { myName:String } } </script>
3. Bus (event bus) brother component communication
Non-parent-child components or more inter-layer components, inter-component transmission values are managed in Vue through a separate event center
- Create a public file
- Exposed Vue instance
- The data passes the party, triggering bus.$emit (method name, data passed) through an event
- The receiving data party, in the life cycle function, listens through bus.$on (method name, [params])
- Destruction event, after the data receiving party is destroyed by bus.$off (method name)
import Vue from "vue" const bus=new Vue() export default bus
Definition calls in components that need to be changed
<template> <div> <div>I'm a communication componentA</div> <button @click="changeName">Modify your name</button> </div> </template> <script> import bus from "@/utils/"; export default { components: {}, data() { return {}; }, mounted() { (bus); }, methods: { changeName() { bus.$emit("editName", "Dataset!"); }, }, }; </script> <style lang='scss' scoped> </style>
Another component also introduces files, and listens to event callbacks through $on
<template> <div> <span>name:{{name}}</span> <div>I'm a communication componentB</div> </div> </template> <script> import bus from "@/utils/"; export default { components: {}, data() { return {name}; }, mounted() { bus.$on("editName", (name) => { =name (name); // }); }, methods: {}, }; </script> <style lang='scss' scoped> </style>
4. $parent, $children directly access component instances
- The child component obtains the parent component instance through ---> $parent
- Parent component obtains child component instance array through ---> $children
Child component --- this.$parent can obtain the parent component's methods, data data, etc., and can be used and executed directly
<template> <div>I'm a child component</div> </template> <script> export default{ name:"Son", data(){ return{ sonTitle: 'I am the data of the child component' } }, methods:{ sonHandle(){ ('I'm a method for child components') } }, created(){ (this.$parent) (this.$) // => I'm the data of the parent component this.$() // => Methods of I'm a parent component } } </script>
Parent component --- Gets the child component instance, and the obtained instance is an array form. This.$children[0] can obtain a component instance and call component methods and data.
<template> <div> <Son>I'm the parent component</Son> </div> </template> <script> import Son from './' export default{ name: 'father', components:{ Son }, data(){ return{ fatherTitle: 'I am the data of the parent component' } }, methods:{ fantherHandle(){ ('I'm the method of the parent component') } }, mounted(){ (this.$children) (this.$children[0].sonTitle) // => I'm the data of the child component this.$children[0].sonHandle() // => I'm a child component method } } </script>
5、$refs
Ref is used to register reference information for elements or child components. The reference information will be registered on the $refs object of the parent component.
Parent component uses $refs to obtain component instances
<template> <div> <Son ref="son"></Son> </div> </template> <script> import Son from './' export default{ name: 'father', components:{ Son }, mounted(){ (this.$) /*Component instance*/ } } </script>
6. Provide/inject (provided/inject) Multi-component or deep-level component communication
provide/inject detailed explanation
- The parent component uses provide to inject data
- Subcomponents use inject use data
/*Parent component*/ export default{ provide: { return{ provideName: 'Selling front-end boy' } } }
At this point, the variable providesName can be provided to all subcomponents below it, including great-grandchildren, grandchildren components, etc. You only need to use inject to obtain data.
/*Subcomponent*/ export default{ inject: ['provideName'], created () { () // => "Selling front-end boy" } }
- The parent component does not need to know which component uses it to provide the data
- The subattachment does not need to know where this data comes from
7. slot (slot-scope scope slot) child element --> parent element (similar to communication)
- Used as a reusable template (that can be passed data) to replace the rendered elements
- In a child component, just pass the data to the slot, just like you pass the prop to the component
- Note: The parent slot receives content is the outermost element and must have the attribute slot-scope
Sub-elements
<template> <div> <div class="isSon"> <slot :info='arrList'></slot> </div> </div> </template> <script> export default { components: {}, data() { return {arrList:[1,'aa','Zhang San']}; }, mounted() { }, methods: { }, }; </script>
Parent element
<template> <div> <SonG> <span slot-scope="props"> <ul> aa <li v-for="item in " :key="item"> {{item}} </li> </ul> </span> </SonG> </div> </template> <script> import SonG from '../components/' export default { components:{ SonG }, data () { return { } } } </script>
8. VUEX Status Management
A warehouse of public data
Provide some methods to manage warehouse data
import Vue from 'vue' import Vuex from 'vuex' (Vuex) export default new ({ state: { }, mutations: { }, actions: { }, modules: { } })
Summarize
This is the end of this article about eight methods of implementing component communication for vue. For more related content on implementing component communication for vue, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!