Vue——父和子组件通信

来源:互联网 发布:red flag linux 8.0 编辑:程序博客网 时间:2024/06/05 07:07

父子通信


props


实例1

html()的数据 传到 js()里的数据


props

HTML<div id = 'app'>    //我们在这里定义了一个变量msg    <alert msg="Yoooo"></alert></div>JStemplate: '<button @click="on_click()">弹框</button>' ,//在这里,props接收了变量msgprops:['msg'],methods: {    on_click: function(){        alert(this.msg)    }}


实例2

动态,实现点击链接,跳转页面。

HTML<user username="lhe"></user>JS//这里的href使用了v-bind绑定变量usernametemplate: '<a :href=" \'/user/\' + username">@{{username}}</a>' ,//接收html的usernameprops:['username'],




子父通信

HTML<user username="lhe"></user>JS//父组件Vue.component('balance',{    template: `        <div>            <!--第一步,父组件监听子组件的show-balance事件。-->            <!--子组件触发事件后,父组件随之触发parent_show_balance事件-->            <show @show-balance="parent_show_balance"></show>            <!--第四步,当show为true的时候,显示-->            <div v-if = "show">                您的余额:¥98            </div>        </div>    `,    methods: {        //第二步,定义parent_show_balance事件,将show变为true。        parent_show_balance (data) {          this.show = true;      }    },    data: function(){        return {            //第三步,在data里面定义show默认为false。            show: false,        }    }});//子组件//第一步,创建子组件showVue.component('show',{            //第二步 当button被点击,触发on_click函数    template: '<button @click="on_click()">显示余额</button>',    methods: {        //第三步,定义on_click函数        on_click(){            //第四步,使用$emit触发show-balance事件            this.$emit('show-balance',{a:1 , b:2})        }    }});new Vue({    el:'#app'})
原创粉丝点击