我们使用vue开发时,往往需要提取公共组件,并且封装组件,因此需要实现父子组件之间相互通信,传递事件发送消息。
1、父组件向子组件传递数据(prop)
父组件向子组件传递数据我们需要用到prop,我们可以通过prop向子组件传递数据,数据类型可以是string、number、boolean、array、object,子组件可以通过props获取到父组件穿的的数据,进行一些操作或者直接渲染,同时prop可以传递动态或者静态的数据。
父组件App.vue代码:
<template>
<div id="app">
<child-node title="静态数据1" :activeData="plugdatas"></child-node>
</div>
</template>
<script>
import ChildNode from './components/ChildNode'
export default {
name: 'App',
data(){
return{
plugdatas:"动态传递的数据2",
}
},
components:{
ChildNode
},
methods:{
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
子组件ChildNode.vue代码
<template>
<div>
<div>静态数据:{{title}}</div>
<div>动态数据:{{activeData}}</div>
</div>
</template>
<script>
export default {
name:"ChildNode",
props:["title","activeData"]
}
</script>
<style>
</style>
单向数据流
所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外改变父级组件的状态,从而导致你的应用的数据流向难以理解。
额外的,每次父级组件发生更新时,子组件中所有的 prop 都将会刷新为最新的值。这意味着你不应该在一个子组件内部改变 prop。如果你这样做了,Vue 会在浏览器的控制台中发出警告。
说明:因为prop是单向向下绑定数据,所以子组件不可通过prop向父组件传递数据,发送消息。
2、子组件向父组件发送消息、传递事件
vue子组件向父组件发送消息,传递数据需要使用 $ emit 触发父组件的自定义事件。这样我们可以实现子组件向父组件传递数据。
用法:vm.$emit(“listenEven”,arg)
listenEven:触发的事件名;
arg:传递的参数
完整代码如下;
父组件App.vue代码:
<template>
<div id="app">
<child-node title="静态数据1" :activeData="plugdatas" @listenEvent="getListenEvent"></child-node>
<div>子组件传递的数据:{{sendValue}}</div>
</div>
</template>
<script>
import ChildNode from './components/ChildNode'
export default {
name: 'App',
data(){
return{
plugdatas:"动态传递的数据2",
sendValue:""
}
},
components:{
ChildNode
},
methods:{
getListenEvent:function(msg){
this.sendValue = msg;
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
子组件ChildNode.vue代码
<template>
<div>
<div>静态数据:{{title}}</div>
<div>动态数据:{{activeData}}</div>
<div>
<input type="text" ref="input1"><button type="button" @click="sendMsg">发送事件</button>
</div>
</div>
</template>
<script>
export default {
name:"ChildNode",
props:["title","activeData"],
methods:{
sendMsg:function(){
let value = this.$refs.input1.value;
this.$emit("listenEvent",value);
}
}
}
</script>
<style>
</style>
我们可以通过这种方式实现父子组件之间相互通信,传递数据。封装我们需要的组件!!!!!