Vue 组件

data必须是函数

模板根元素只能一个

模板props中的属性

字符串数组形式
如果是驼峰命名,父组件传值是短横线命名

传值 或 传事件

: props中的属性=“父组件数据”
@子组件事件=“父组件事件”

子组件向父组件传值

因为props中的数据是单向传递的,所以修改不影响父组件数据
子组件调用时,设置:@子组件事件=“父组件事件”
this.$emit(子组件事件函数名(字符串类型),参数)

兄弟组件传值

  1. 创建事件中心
  2. 在mouted生命周期函数中注册事件
  3. 使用eventBus.$on注册,注意要用箭头函数,以免内部无法访问this
  4. 使用eventBus.$emit触发
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<body>
    <div id="components-demo">
        <button-counter></button-counter>
        <button-counter2></button-counter2>
    </div>
</body>
<script>
    // 提供事件中心
    var eventBus=new Vue();

    // 定义一个名为 button-counter 的新组件
    Vue.component('button-counter', {
    data: function () {
        return {
            count: 0
        }
    },
    template: '<button v-on:click="handle">clicked me {{ count }}</button>',
    methods:{
        handle(){
            eventBus.$emit('add2',1)
        }
    },
    mounted(){
        eventBus.$on('add',(val)=>{
            this.count+=val
        })
    },
    })

    Vue.component('button-counter2', {
        data: function () {
            return {
                count: 0
            }
        },
        template: '<button v-on:click="handle">clicked me {{ count }}</button>',
        methods:{
            handle(){
                eventBus.$emit('add',2)
            }
        },
        mounted(){
            
            eventBus.$on('add2',(val)=>{
                this.count+=val
                console.log(this.count);
            })
        },
    })

    var app=new Vue({
        el:'#components-demo',
            data(){
                return {

                }
            }
        })
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值