1. Reference the third-party library mitt
npm install mitt
2. Create the utils folder under the project src folder, and create mitt.js in utils , the code in mitt.js is as follows:
import mitt from "mitt"; export default new mitt();
3. Example: Component A passes value to component B
//在组件A中引入 import mitt from "@/utils/mitt"; //调用传值 mitt.emit("mittClick", "数据数据数据");
//在组件B中引入 import mitt from "@/utils/mitt"; //接收传值 mitt.on("mittClick", (val) => { console.log(val)//数据数据数据 })
Use an empty Vue instance to pass the value, just use $emit, $on.
<!DOCTYPE html> <html lang="zh-CN"> <head> <title></title> <meta charset="utf-8"> <script src="./main/vue.js"></script> </head> <body> <div id="demo"> <!-- test code --> <custom-a></custom-a> <custom-b></custom-b> <!-- test code --> </div> </body> <script type="text/javascript"> let bus = new Vue(); Vue.component("custom-a", { template: '<button @click="transValue">Click</button>', methods: { transValue: () => bus.$emit("transValue", "hello from a") } }); Vue.component("custom-b", { template: '<input :value="msg">', data: function() { return { msg: "" } }, mounted() { bus.$on("transValue", msg => this.msg = msg) } }); new Vue({ el: "#demo" }); </script> </html>
The above is the detailed content of How to solve the problem of mutual value transfer between vue3 subcomponents. For more information, please follow other related articles on the PHP Chinese website!