vue组件间通信

来源:互联网 发布:cf改枪软件 编辑:程序博客网 时间:2024/05/22 15:32

父->子 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>
原创粉丝点击