子向父组件通信,需要用到自定义事件,使用v-on:xxx 或@:xxx ,它除了监听DOM事件外,
还可以用于组件之间的自定义事件
子组件使用 $emit()来触发事件 父组件使用$on()来监听子组件的事件
--------------------------------------
除了用 v-on || @ 在组件上 添加自定义事件外,也可以监听DOM事件,这时需要用.navtive修饰符
表示监听一个原生事件,监听的是该组件的根元素
代码如下:
<three :outdata="a" @click.native="changeA"/>
父组件模板
<template>
<div id="app">
{{ a }}
<!-- 使用组件 @changeNew是子组件定义的名字 changeA 是父组件定义的方法名,
因为父想接收子组件传来的值,只能通过方法接受 -->
<three :outdata="a" @changeNew="changeA"/>
</div>
</template>
<script>
import three from './components/three'
export default {
components:{
three
},
data(){
return {
a:"我是父组件的值"
}
},
methods:{
//event 参数是接收 子组件传来的值,可以自己打印一下
changeA(event){
this.a = event
}
}
}
</script>
子组件模板
<template>
<div class="three">
<!-- {{ outdata }} -->
<br>
<button @click="change">改变父组件的值</button>
</div>
</template>
<script>
export default {
props:{
outdata:{
type:String,
default:''
}
},
data(){
return{
}
},
methods:{
change(){
// 两个参数 参数1:自定义的事件名字 参数2:传给父组件的值
this.$emit('changeNew',"我被改变了!")
}
}
}
</script>
子向父组件传值 第二种写法 在子组件上 使用 v-model 指令
父组件模板
<template>
<div id="app">
{{ a }}
<!-- 使用组件 使用v-model -->
<three :outdata="a" v-model="a"/>
</div>
</template>
<script>
import three from './components/three'
export default {
components:{
three
},
data(){
return {
a:"我是父组件的值"
}
},
methods:{
changeA(event){
this.a = event
}
}
}
</script>
子组件模板
<template>
<div class="three">
<!-- {{ outdata }} -->
<br>
<button @click="change">改变父组件的值</button>
</div>
</template>
<script>
export default {
props:{
outdata:{
type:String,
default:''
}
},
data(){
return{
}
},
methods:{
change(){
//传入一个特殊的 input
this.$emit('input',"我被改变了!")
}
}
}
</script>