vue组件间通信

父->子 pass props
子->父 emit event

一、props

父组件:

<child message="hello!"></child>

子组件:

<template>
    <div id="child">
        <span>{{message}}</span>
    </div>
</template>
<script type="text/javascript">
    export default{
        props:['message']
    }
</script>

主要是message,在父组件使用时添加message,传递参数,在子组件通过props接受message,然后再在子组件中渲染出来。
props的数据可以向data里的数据一样在组件模板内部使用。也可以this.message使用

关于命名方式 组件的命名:my-comp/myComp

这两个等价,但是在页面渲染使用时只能myComp使用。

**

动态props

**

就是将从父组件传入的值动态传入:这里使用input实现
父:

<input type="text" name="toChild" v-model="toChild">
<child :message="toChild"></child>//数据绑定

//toChild的声明
data(){
    return{
        toChild:''
    }
  }

子组件不变

对于props:
prop验证:

props:{
            'message':Number
        }

这种的。
**

二、event

**
子->父
使用v-on的自定义事件
1、使用 on(eventName)2使 emit(eventName)触发事件

例子:
父:

 <child :message="toChild" @my-event="fromChild"></child>
    <span>{{fromChildData}}</span>



//
fromChild(msg){
      this.fromChildData=msg;
    }

子:

<template>
    <div id="child">
        <span>{{message}}</span>
        <button v-on:click="toFather">emit</button>
    </div>
</template>
<script type="text/javascript">
    export default{
        props:{
            'message':String
        },
        data(){
            return{
                data:'555'
            }
        },
        methods:{
            toFather(){
                this.$emit('my-event',this.data)
            }
        }
    }
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值