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
Release: 2023-05-17 20:19:04
forward
1375 people have browsed it

Vue3 sub-components pass values ​​to each other

1. Reference the third-party library mitt

npm install mitt
Copy after login

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();
Copy after login

3. Example: Component A passes value to component B

//在组件A中引入
import mitt from "@/utils/mitt";

//调用传值
mitt.emit("mittClick", "数据数据数据");
Copy after login
//在组件B中引入
import mitt from "@/utils/mitt";

//接收传值
mitt.on("mittClick", (val) => {
    console.log(val)//数据数据数据
})
Copy after login

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>
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template