Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize component Communication with vue

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces vue how to achieve component communication, the article introduces in great detail, has a certain reference value, interested friends must read it!

Preface

In vue, there are no more than three relationships between components:

Components need to communicate, in development, the commonly used communication methods are: vuex, eventBus, and props and emit, $parent and $children, in addition, there are provide and inject, $attrs and $listeners and so on.

1. Vuex

I'm sure you've used this a lot, so let's briefly review:

State: where to put the status

Mutation: the only place where the state is modified. Asynchrony is not supported.

Action: change the state by calling the methods in Mutation, and support async

Getter: can be understood as a computational attribute

Module: modules, each with its own state, mutation, action, getter

For simple use, without going into detail here, mention the namespaces in module.

If you want your module to be more encapsulated and reusable, you can make it a module with a namespace by adding namespaced: true. When a module is registered, all its getter, action, and mutation are automatically named according to the path to which the module is registered

In this way, we can use it like this when we use it:

II. EventBus

This is called the event bus, and take a brief look at how it is used:

Initialization

The first step is to initialize an eventBus, which can be bound to a vue prototype or to a window object, and can be extracted as a module to be introduced when needed. Here we bind directly to the vue prototype:

Create and delete events

Create and delete events on the required components:

Trigger event

Finally, it triggers the event where it is needed.

III. Props/emit

Needless to say, this should be the most frequently used communication between father and son. Of course, if you use sub-components as a springboard, you can also communicate between grandparents and grandchildren, but it is more troublesome. This is not recommended.

4. $parent/$children

$parent directly accesses the parent instance, while $children returns an array of instances. So I usually use $parent with $refs.

5. $attrs/$listeners

These two may be used less. Let's take a look at the introduction on the official website:

To put it simply, $attrs receives all binding properties except prop, style, and class, and $listeners receives all binding events except those modified by .native. Let's take a look at the following examples:

Parent component

Sub-component

Import Son from ". / son.vue"; export default {components: {Son}, provide () {return {father: this.formData,};}, data () {return {formData: {inputValue: "123",}, otherValue: 999,};}, methods: {success (data) {console.log (data) }, handleInput () {},},}; export default {props: {inputValue: String,}, created () {console.log (this.$attrs, "son---$attrs"); console.log (this.$listeners, "son---$listeners");}, methods: {handleChange () {this.father.inputValue = this.inputValue;},},}

According to the previous understanding, $attrs should only receive otherValue,$listeners and only success events. Take a look at the printed result:

The result is indeed the same. In addition, it can be passed to the grandson component:

Import GrandSon from ". / grandSon.vue"; export default {components: {GrandSon}, props: {inputValue: String,}, created () {console.log (this.$attrs, "son---$attrs"); console.log (this.$listeners, "son---$listeners");}, methods: {handleChange () {this.father.inputValue = this.inputValue;},},} Export default {props: {inputValue: String,}, created () {console.log (this.$attrs, "grandSon---$attrs"); console.log (this.$listeners, "grandSon---$listeners");}, methods: {handleChange () {this.father.inputValue = this.inputValue;},},}

In this way, communication is also realized between grandparents and grandchildren.

VI. Provide/inject

Provide/inject can inject a dependency into all its descendant components in an ancestor component, as long as the upstream and downstream relationships are established. The simple understanding is that provide is about injecting data, and inject is about getting data. So provide is for parent components and inject is for descendant components. Provide should be an object or a function that returns an object, and inject should be an array of strings or an object. The official website mentions the following sentence:

Tip: provide and inject bindings are not responsive. It was done on purpose. However, if you pass in a listenable object, the property of the object is responsive.

How do you understand this sentence? Literally, if you want the data passed upstream and downstream to be responsive, you should pass it in the form of an object. Try passing it in the form of a basic data type first. Take a look at the example:

Parent component:

Parent component

Sub-component

Sun component

Import Son from ". / son.vue"; import GrandSon from ". / grandSon.vue"; export default {components: {Son, GrandSon}, provide () {return {father: this.inputValue,};}, data () {return {inputValue: "123",};},},}

Subcomponents:

Export default {inject: ["father"], data () {return {inputValue: ",};}, watch: {father (val) {console.log (val," val "); this.inputValue = val;},}, created () {console.log (this," this ");}, methods: {handleChange () {this.father.inputValue = this.inputValue },},}

Print the this in the subcomponent:

As you can see, the inputValue value of the parent component is injected into the child component. But the father can't be picked up.

Then we inject it in the form of an object:

Parent component

Sub-component

Sun component

Import Son from ". / son.vue"; import GrandSon from ". / grandSon.vue"; export default {components: {Son, GrandSon}, provide () {return {father: this.formData,};}, data () {return {formData: {inputValue: {inputValue: "123",},};},},} Export default {inject: ["father"], data () {return {inputValue: ",};}, watch: {'father.inputValue' (val) {console.log (val," val "); this.inputValue = val;},}, created () {console.log (this," this ") }, methods: {handleChange () {this.father.inputValue = this.inputValue;},},}

At this point, let's take a look at the printed this and its effect:

In this way, the response of the data can be realized. It is important to note that if the this of the entire parent component is injected into the descendant component in the parent component, the injected object cannot be monitored through deep snooping in the descendant component, and a stack overflow error will be reported. So here I'm using this.formData form injection. In this way, you can listen in the descendant component in the form of 'father.inputValue', or you can listen in this form:

Father: {handler (val) {console.log (val)}, deep: true,}

As for why this problem is caused, let's take a look at the implementation of in-depth monitoring:

What does this comment mean? the simple understanding is that vue collects the properties of the object to listen by recursively traversing every property in the object. It is well known that recursion can easily cause stack overflows, and it is not difficult to understand why this objects cause stack overflows (too many and nested layer by layer).

These are all the contents of the article "how to implement component Communication in vue". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report