vue --- > 模块从子组件获取数据

先看个一般的例子:

// 我们需要将信息从子组件传递给父组件,(有可能不止一条信息,因此)肯定需要一个标识,这个标识放在$emit里面(js),在dom中通过@来关联父元素。如下:


<div id = "app">
    <transfer @connect="sayConnect" @build="sayBuild"></transfer>
</div>


// js 
<script>
    Vue.component('transfer',{
        template:
        '<button @click="send1">发送connect</button><br>'+
        '<button @click="send2">发送build</button>',
        methods:{
            send1(){
                this.$emit('connect');
            },
            send2(){
                this.$emit('build');
            }
        }
    });
    // 子组件注册了2个方法,send1和send2,点击send1发送connect,点击send2发送build.
    // @connect="sayConnect",  connect对应子组件中this.$emit('connect').sayConnect对应父组件的sayConnect方法,下面写出来.
    // 注意,在子模版中,按钮的绑定使用的是@而不是:



    let vm = new Vue({
        el:"#app",
        methods:{
            sayConnect(){
                console.log('connect success!');
            },
            sayBuild(){
                console.log('build success');
            }
        }
    });
</script>

在这里插入图片描述在这里插入图片描述

接下来,看个更复杂一点的例子:

假设我们希望:
在这里插入图片描述
点击"+1",总数加1;点击"-1"总数减1. 且数据是来自子组件…

首先写html

<div id = "app">
    <p>总数 {{ total }} </p>
    <my-component @increase="handleTotal" @reduce="handleTotal"> </div>
</div>
// 说明: total 是父元素的
// @increase 对应 子组件中的 $emit('increase', data);
// @reduce 对应 子组件中的 @emit('reduce', data);
// handleTotal对应父组件中methods方法中的 handleTotal方法

挂载Vue,注册组件

<script>
    // 组件应该在vue挂载之前注册
    Vue.component('my-component',{                      // 第一个参数组件名,对应html中的<my-component></my-component>
        // 首先写替换<my-component>的template
        template:'\
        <div>\
            <button @click = "handleIncrease"> +1 </button>\
            <button @click = "handleReduce">-1 </button>\
        <div>',
        // ps: template中 写了2个点击事件 handleIncrease 和 handleReduce , 由于要传一个数据给父元素,我们定义如下:
        data: function (){
            return {
                counter: 0;
            }
        },    // 子元素中的counter 初始化为0
        methods: {
            handleIncrease: function() {
                this.counter++;
                this.$emit('increase', this.counter);
            },
            handlerReduce: function() {
                this.counter--;
                this.$emit('reduce', this.counter);
            }
        }
    }); 
    // 子模块完毕
    // 说明: $emit(a,data)用来像父元素传递信息, 父元素用@'a'的形式接受信息
    
    // 开始挂载vue(在此是父元素).
    var app = new Vue({
        el: '#app',
        data: {
            total: 0     // 对应html <p>{{total}} </p>
        },
        methods:{
            handleTotal: function (total ){    // total 参数来自于 $emit的第二个参数..
                     this.total = total;            
            }
        }
    })
 </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值