您现在的位置:首页 >> 前端 >> 内容

vue组件间通信教程

时间:2017/10/20 8:45:00 点击:

  核心提示:父-子 pass props子-父 emit event一、props父组件:child message=hello!/child子组件:templatep id=childspan{{message...
父->子 pass props

子->父 emit event

一、props

组件

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

子组件:

<template>
    <p id="child">
        <span>{{message}}</span>
    </p>
</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>
    <p id="child">
        <span>{{message}}</span>
        <button v-on:click="toFather">emit</button>
    </p>
</template>
<script type="text/javascript">
    export default{
        props:{
            'message':String
        },
        data(){
            return{
                data:'555'
            }
        },
        methods:{
            toFather(){
                this.$emit('my-event',this.data)
            }
        }
    }
</script>

 

Tags:VU UE E组 组件 
作者:网络 来源:Shellin_F的