SoFunction
Updated on 2025-04-06

vue uses pinia to achieve global seamless communication

Preface

There are more than a dozen data communication methods in vue, including father and son, brothers, intergenerational transmission, and unrelated transmission. Each of these dozen methods has its own different syntax, which means that we need to choose the most suitable communication method based on the relative relationship of these components. We are always using various forms of parameter transmission. MD, it looks like our chaotic front-end frame circle.

mqtt protocol

MQTT (Message Queuing Telemetry Transport, Message Queuing Telemetry Transport), is a type ofPublish/Subscribepublish/subscribe) mode "lightweight" communication protocol, built on the TCP/IP protocol, released by IBM in 1999, is suitable for low-performance IoT devices.

Why should we mention mqtt? Because what I will talk about next is closely related to mqtt's communication method.

First, let’s briefly introduce the mqtt thing. Simply put, it consists of three parts: server (mqtt broker), publisher (publisher), and subscriber (subscriber). The identities of publishers and subscribers are usually mixed, that is, a user can be both a publisher and a subscriber. When publishing a message, it is the publisher, and when subscribed, it is the subscriber.

When publishing a message, you need to specify a topic, and of course, you also need to specify a topic when subscribing. When publishing a message to a topic, the server will distribute the message to all clients subscribing to the topic, and when the subscriber receives it, it will perform its next operation based on the message content.

For example, it is probably: you (subscriber) tell your mother (server) that your younger brother (poster) will tell you that you can hit him, and then your mother agreed (subscribe successfully), and the moment your younger brother played the game (released), the news was captured by your mother and sued you, and you successfully hit your younger brother.

In the example above, you subscribe to the message and then do something

Post Subscription Thought

We all know that the two-way binding principle of vue is based on the publishing and subscription paradigm (must-have for interviews, yes, buddy). I believe you are like me. Even if you read the principle of vue two-way binding several times, you still don’t understand this word. What is the publish subscription paradigm? Publish subscription is everywhere in life and programming. It is a popular meaning, not a proprietary term for programming.

In fact, watch/watchEffect in vue is a subscription manifestation.

watch(someValue,()=>{
    // ... 
})

The above code has been subscribedsomeValueofThe value change event. But it seems that the publisher is missing in this example, but the publisher actually exists implicitly.

someValue = otherValue

At this time, thisjs statementBecome a publisher.

The watch method in vue3 is very powerful. It supports deep monitoring, listening to objects, single attributes under objects, multivariate monitoring, etc.

Implement global event publishing subscription using watch and pinia

Through the above description, it is not difficult to find that using watch to listen to certain attributes in pinia can achieve the effect of subscription, thereby achieving barrier-free transmission of parameters/communication. So is it feasible for us to use pinia for all scenarios involving transmission of parameters and communication?

I think it is feasible. Passing parameters in this way does not need to consider where the value comes from and where it will go. Watch wherever you use it.

Applicable scenarios

This way of writing that monitors global variable changes and performs the next operation sounds like a great impact on performance. In fact, pinia has already made a relatively appropriate mechanism for this. First of all, Pinia store relies onpiniaInstances share the same store instance in all calls. You can define as many stores as you like, and these stores will not occupy memory separately, so you can just create a store in multiple files with confidence.

For example, there is now a global map componentmapboxThere are several widgets that control the addition, deletion, modification and search of layers on the map. We do not need to use them in each component.mapboxComponent pass values, or userefGet the example, we just need to put the required data into pinia, and thenmapboxListen to it within the component.

// 
watch(() => , (newValue) => {
  renderGrid(newValue)
})

Listen in the above codeData, when its data changes, re-render this data. Of course, if you need to clear it, just empty the data. You can add new empty data to the monitoring process, orrenderGridProcessed in the function.

In this way, all components, no matter where they are located, or what path, can achieve similar value transmission effects as long as they listen to the changes of a certain value.

Potential problems

Memory leak

Of course, there is no perfect thing in the world. Under normal circumstances, doing this has almost no impact on performance, but once a problem occurs, it will be fatal. Although pinia instances are singletons, references are not. Every time a watch to the store value is added, a reference to this value will be added. Under normal circumstances, vue will actively remove these watches when the page is destroyed. However, if the watch is placed in the asynchronous body, you need to pay attention to manually remove them, otherwise these memory will be permanent, that is, memory leaks.

A dead cycle

Relying entirely on watch to perform operations will inadvertently cause dead loops or stack overflow problems. Give an example

watch(()=>,()=>{
     = otherValue
})

If the value of otherValue is a fixed value, it will no longer enter the next time because the value has not changed again, but if the value is not a fixed value, it is easy to see that this watch is actually a dead loop when the operation is done.After the value of , it will return to this watch. It is also very simple to avoid this problem. Just like the usual recursive function, just give it a condition to jump out.

watch(()=>,(nv)=>{
    if(nv == someValue) return
     = otherValue
})

No problem triggering

When a certain value listened to does not change, the watch will not trigger, which will lead to another problem. If some operations are relied on the change of a certain value, and this operation and the change of this value are not bidirectionally coupled, the watch will not be triggered when assigning a value to a certain value.

For example, by valuegoNewAreato redirect the map to a new regional perspective.

watch(()=>,()=>{
    ({
    // ...
    })
})

For example, there is a button that will be assigned asBeijing, then the map jumps to Beijing normally. If we pull the map perspective at this time, the actual area becomesShanghai, then assign it toBeijingWhen the map will not trigger a jump becauseNo change.

To solve this problem, you should put a blank value. Right now:

watch(()=>,()=>{
    ({
    // ...
    })
    ('moveend',()=>{
         = ""
    })
})

As mentioned above, doing so will cause the watch to repeatedly trigger the dead loop, so I would like to add another sentence:

watch(()=>,(nv)=>{
    if(nv == "") return
    ({
    // ...
    })
    ('moveend',()=>{
         = ""
    })
})

Summarize

Use watch and pinia global variables to achieve global event control, which simplifies the development process to a certain extent. To be honest, it is very pleasant to write and very clear. However, once more variables are added, the introduction to mutual influence will increase, and managing huge watches is also a burden. You need to always be careful not to overflow memory or cycle.

In short, this writing style is full of flexibility, but it requires a very clear idea and a deep understanding of the business in order to be at ease.

This is the end of this article about vue using pinia to achieve global seamless communication. For more related content on vue pinia global seamless communication, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!