Home > Article > Web Front-end > An article briefly analyzing the usage of message subscription and publishing in Vue
What is message subscription and publishing? how to use? The following article will introduce to you how to use message subscription and publishing in Vue. I hope it will be helpful to you!
Message subscription and publishing is a method of communication between components, suitable for Communication between arbitrary components. Can better realize communication between components (message subscription and publishing are like a newspaper delivery boy. For example, Xiao A subscribes to a newspaper and then leaves his own information in the newspaper office, and then the newspaper delivery boy presses the The message left by a found the place where little a was and gave him the newspaper)
1. First we need to install pubsub, Open vscode → open the terminal → enter the installation command (you can also install it in cmd) [Related recommendations: vuejs video tutorial, web front-end development]
npm i pubsub-js
2 .Introduction (just introduce it into the component that needs to use pubsub)
import pubsub from ' pubsub-js'
3. Receive data If component A wants to receive data, subscribe to the message in component A, and the subscribed callback remains in component A itself.
methods(){demo(data){.....}mounted() {this.pid = pubsub. subscribe( 'xx',this . demo) }
We should first find the component that wants to receive data, configure a mounted configuration item, and subscribe to the message subscribeThis word also means to subscribe, as well. The following component is the role of Little A. He wants to subscribe to a newspaper, and then leaves his address 'hello', and then uses the callback to obtain the data. The msgName and data here are respectively Subscription name and data (that is, Xiao A’s home address and the newspaper carried by the newspaper delivery boy)
import pubsub from "pubsub-js"; export default { name: "School", data() { return { name: "山鱼特效屋", address: "南京北城区" }; }, mounted() { this.pubId = pubsub.subscribe("hello", (msgName, data) => { console.log("该消息已经发布", msgName, data); }); }, //使用完之后销毁该绑定事件避免后期错误使用 beforeDestroy() { pubsub.unsubscribe(); } };
Provide data
pubsub. publish( ' xxx' ,数据)
The first parameter 'hello' of the publish method is the subscription name, and the second parameter (this.name) is the data you want to pass.
import pubsub from "pubsub-js"; export default { name: "Student", data() { return { name: "张三", sex: "男" }; }, // 配置一个methods项 methods: { snedStudentName() { // 选择给谁提供数据 pubsub.publish("hello", this.name); } } };
It is best to unsubscribe in the beforeDestroy hook.
beforeDestroy() {pubsub.unsubscribe();}
vuejs introductory tutorial, Basic programming video)
The above is the detailed content of An article briefly analyzing the usage of message subscription and publishing in Vue. For more information, please follow other related articles on the PHP Chinese website!