
vuejs开发:组件之间的通讯。
1、父组件向儿子组件传递数据的方式就是通过 Prop 向子组件传递数据。
//child.vue
<template>
<div>
我是儿子,我收到来自父亲的数据为 {{value}}
</div>
</template>
<script>
export default {
props:{
value: String
}
}//App.vue
<template>
<div id="app">
<Child :value="x" />
</div>
</template>
<script>
import Child from './components/Child'
export default {
data(){
return {
x: 'hi,child'
}
},
components:{
Child
}
}
</script>2、儿子组件向父组件传递数据的方式就是通过子组件内 $emit 触发自定义事件,子组件使用时 v-on 绑定监听自定义事件。
这里的 v-on 事件通信是在子组件使用时作为子组件的事件属性自动进行监听的。
因此儿子组件向父组件传递数据,依赖于子组件使用时的自定义事件属性。
//child.vue
<template>
<div>
我是儿子,我收到来自父亲的数据为 {{value}}
<button @click="sayHi">
向父组件打招呼
</button>
</div>
</template>
<script>
export default {
props:{
value: String
},
methods:{
sayHi(){
this.$emit('sayHi','hi,parent!');
}
}
}
</script>//App.vue
<template>
<div id="app">
我是父组件,我收到子组件传来的数据为 {{y}}
<Child :value="x" @sayHi="y = $event"/>
</div>
</template>
<script>
import Child from './components/Child'
export default {
data(){
return {
x: 'hi,child',
y: ''
}
},
components:{
Child
}
}
</script> 


网友评论文明上网理性发言 已有0人参与
发表评论: