Vue组件之间的数据传递分为四种方式
- 父->子:props
传递数据
传递其他类型的数据:
传递函数:除了传递数据,还可以传递函数,就是子组件调用父组件的方法,如下所示:
2、子->父:$emit
子组件:
<template>
<div>
<button @click="sendMsgToParent">向父组件传值</button>
</div>
</template>
<script>
export default {
methods: {
sendMsgToParent:function () {
this.$emit("childMsg","hello world!");
}
}
}
</script>
父组件
<template>
<div id="app">
//@childMsg 与子组件中this.$emit("childMsg","hello world!")起的名字一致
<child @childMsg="showChildMsg"></child>
</div>
</template>
<script>
import child from './components/Child'
export default {
name: "app",
components: {
child
},
methods:{
showChildMsg:function (data) {
console.log(data);
}
}
}
</script>
- 插槽传递内容:slot(既可以传递数据也可以传递标签):插槽实质是对子组件的扩展,通过
<slot>
插槽向子组件内部指定位置传递内容。 - 如果想了解更多点击如下链接:Vue中组件神兵利器,插槽Slot!
- 非父子组件间的通信:采用第三方库来实现,如通过pubSubjs库来实现。
安装pubsub.js
发布消息:发布changeNum消息:
注意:订阅消息写在created里面,接收changeNum消息