您好,欢迎访问一九零五行业门户网

vue组件之间相互传递数据的实现方法(代码)

本篇文章给大家带来的内容是关于php协成实现的详解(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1、子组件给父组件传递数据
<body>    <div id="app">        父组件:{{total}}        <br>        <son-component v-bind:total="total"></son-component>    </div>    <script>         vue.component('son-component',{            template:'<div>子组件:{{total}}+{{num}}={{add}}</div>',            props:{                total:number            },            data(){                return {                    num:10                }            },            computed:{                add:function(){                    return num=this.total+this.num                }            }        })        var app=new vue({            el:'#app',            data:{                total:1            },                   })    </script></body>
通过v-bind动态绑定父组件中要传递的数据,子组件通过props属性接收父组件传递的数据。
2.父组件给子组件传递数据
<body>    <div id="app">        <son-component v-on:change="getdata"></son-component>        <br>        {{total}}    </div>    <script>        vue.component('son-component',{            template:'<button v-on:click=senddata>点击我向父组件传值</button>',            data(){                return{                    count:1                }            },            methods:{                senddata:function(){                    this.$emit('change',this.count)                }            }        })        var app=new vue({            el:'#app',            data:{                total:1            },            methods:{                getdata:function(value){                    this.total=this.total+value                }            }        })    </script></body>
自定义一个事件,在子组件中通过this.$emit()触发自定义事件并给父组件传递数据,在父组件中监听自定义事件并接收数据。
3.非父子组件之间的通信
<body>    <div id="app">            <a-component></a-component>            <b-component></b-component>    </div>    <script>        vue.component('a-component',{            template:`                <div>                    <span>a组件的数据:{{num}}</span><br>                    <button v-on:click="senddata">击我向b组件传递数据</button>                </div>            `,            data(){                return {                    num:1                }            },            methods:{                senddata:function(){                    this.$root.bus.$emit('change',this.num)                }            }        })        vue.component('b-component',{            template:`                <div>b组件接收a组件数据后相加的数据:{{count}}</div>            `,            data(){                return {                    count: 10                }            },            created:function(){                this.$root.bus.$on('change',(value)=>{                    //alert(value)                    this.count=this.count+value                })            }        })        var app=new vue({            el:'#app',            data:{                bus:new vue()            },        })    </script></body>
以上就是vue组件之间相互传递数据的实现方法(代码)的详细内容。
其它类似信息

推荐信息