0
点赞
收藏
分享

微信扫一扫

Vue组件通信之父子组件通信探讨分析

舍予兄 2022-03-25 阅读 183

开篇

先来一张图:
在这里插入图片描述
在这里插入图片描述
了解组件通信首先要了解自定义事件,因为当子组件向父组件传递数据时,就要用到他

1.1分类

组件通信可以分为:父子组件通信、兄弟组件通信、跨级组件通信

当子组件向夫父组件传递数据时就要用到,v-on除了监听DOM事件外,还可以用于组件的自定义事件子组件使用$emit()来触发事件,父组件用$on()来监听父组件也可以直接在子组件的自定义标签上使用v-on来监听子组件触发的自定义事件

1.2案例

🙋‍♀️🙋‍♀️那就来看一个例子

<div id="app">
        <p>总数:{{total}}</p>
        <my-component @increase="handleGetTotal" @reduce="handleGetTotal">
        </my-component>
    </div>
<script>
     Vue.component('my-component', {
       template: '\
       <div>\
        <button @click="handleIncrease">+1</button>\
        <button @click="handleReduce">-1</button>\
        </div>',
        data: function(){
            return {
                counter: 0
            }
        },
        methods: {
            handleIncrease: function(){
                this.counter++;
                this.$emit('increase', this.counter);
            },
            handleReduce: function(){
                this.counter--;
                this.$emit('reduce', this.counter)
            }
        },
});
    var app = new Vue({
        el: '#app',
        data: {
            total: 0
        },
        methods: {
            handleGetTotal: function(total){
                this.total = total;
            }
        }
    })
</script>

在这里插入图片描述
上述的代码是非常基础也是比较经典的一段理解父子组件之间通信的代码,简单分析一波:相信我,下面这张图如果你能够理解,那么恭喜你,你成功入门,这就是要自己深度理解的一个过程,花个一两分钟深入一下,事倍功半🍍
在这里插入图片描述
在这里插入图片描述

使用v-model玩玩

v-model的最大的特点:双向绑定,注意,是双向,双方谁变了都会变,ok,那再来看一个例子

<div id="app">
    <p>总数:{{total}}</p>
    <my-component v-model="total"></my-component>
    <button @click="handleGetTotal">点我试试!!</button>
</div>
<script>
     Vue.component('my-component', {
       props: ['value'],
       template: '\
       <input :value="value" @input="updateValue">',
        methods: {
            updateValue: function(event){
                this.$emit('input', event.target.value);
            }
        },
       
});
    var app = new Vue({
        el: '#app',
        data: {
            total: 0
        },
        methods: {
            handleGetTotal: function(){
                this.total--;
            }
        }
       
    })
</script>

效果图截图
在这里插入图片描述

在这里插入图片描述
再来分析一波!!
在这里插入图片描述

举报

相关推荐

0 条评论