Home >Web Front-end >Vue.js >How to solve the problem of mutual value transfer between vue3 subcomponents

How to solve the problem of mutual value transfer between vue3 subcomponents

PHPz
PHPzforward
2023-05-17 20:19:041381browse

Vue3 sub-components pass values ​​to each other

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)//数据数据数据
})

Vue different components pass values ​​to each other

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: &#39;<button @click="transValue">Click</button>&#39;,
        methods: {
            transValue: () => bus.$emit("transValue", "hello from a")
        }
    });
    Vue.component("custom-b", {
        template: &#39;<input :value="msg">&#39;,
        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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete