Value transfer between non parent and child components (bus / bus / publish subscribe mode / observer mode)

Time:2021-11-21
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    < title > non parent-child component value transfer (bus / bus / publish subscribe mode / observer mode) < / Title >
    <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<!-- Use vuex or bus mechanism to solve the problem of value transfer of non parent and child components -- >
<!-- Case description: when you click Dell, you will see Lee. When you click Lee, Dell will become Lee

Transfer between two unrelated components
-->
    <div id="app">
        <child content="Dell"></child>
        <child content="Lee"></child>
    </div>
</body>
<script src="../node_modules/vue/dist/vue.min.js"></script>
<script>
    Vue.prototype.bus = new Vue()


    Vue.component('child',{
        data(){
            return {
                selfContent: this.content
            }
        },
        props:{
          content:String
        },
        template:'<div @click="handleClick">{{selfContent}}</div>',
        methods:{
            handleClick(){

                //1. I want to pass the current this.content to another component
                this.bus.$emit('change',this.selfContent)
            }
        },
        mounted(){
            var this_ = this
            //2. Monitor the change time in the bus
            //3. Note: we cannot modify the value passed from the parent component, such as content. We define the attribute in data. If this.content is stored in it, we can operate this attribute
            this.bus.$on('change',function (msg) {
                this_.selfContent = msg
            })
        }
    })
    let app = new Vue({
        el:"#app",

    })

</script>
</html>

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

OSG compilation and installation – MSVC

OSG compilation and installation – MSVC 1. Preparatory work 1.1 environment Windows10 Qt5.14.2 Microsoft Visual Studio2017 cmake-3.20.4-windows-x86_64.msi   1.2 OSG Download osgOfficial website github OSG source code(OpenSceneGraph) Download URL You can also use git to download: git clone –branch OpenSceneGraph-3.6.5 https://github.com/openscenegraph/OpenSceneGraph.git   Dependency Library(3rdParty) Download address Here, select the compiledVisualStudio 2017Version Library Data resources(OpenSceneGraph-Data) Download […]