Vue 组件通信
父子组件之间的通信
官网定义
父子组件之间的通信关系可以总结为prop为向下进行传递,事件向上进行传递。父组件通过prop给子组件下发数据,子组件通过事件给父组件发送消息。
- 子组件的props选项能够接受来自父组件数据。 props是单向绑定,传递方式只能是父到子
- ref 是被用来给元素或子组件注册引用信息的。引用信息将会注册在父组件的 $refs 对象上。
- $emit 绑定一个自定义事件event,当这个这个语句被执行到的时候 就会将参数arg传递给父组件,父组件通过@event监听并接收参数。
- vue2.4以后支持$attr $listeners,实现A=>B=>C三层
props
父组件code:
//props示例(vue)
<template>
<div id="app">
<child :message="message"></child>
</div>
</template>
<script>
import Child from "./Child";
export default {
components: {
Child},
name: "main-page",
data() {
return {
message:{
type:1,
name:'Admin',
},
a:2,
b:4,
c:'lalal'+Math.random(),
title:'',
info:'我是来自父组件',
msg:'默认'
}
},
created() {
},
mounted(){
// this.$refs.temp.getMessage()
},
methods: {
}
}
</script>
<style lang="scss" scoped>
#app {
width: 375px;
height: 100%;
}
</style>
子组件code:
// props示例(vue)
<template>
<div>
{
{
message}}
<!--<slot></slot>-->
</div>
</template>
<script>
export default {
name: "child",
props:['message'],
data() {
return {
title:''
}
},
mounted() {
// this.$emit('showMessage','我是来自子组件')
},
methods:{
}
}
</script>
<style lang="scss" scoped>
@import "../../src/style/base/variables";
</style>
父组件code引用子组件,通过props可以实现传值。可以传递string , number , object,表达式。对于子组件接受父组件props,可以直接使用props:[‘xxxx’]格式,为了更严谨,可以使用如下方式:
<script>
export default {
name: "child",