父组件是通过props属性给子组件通信的(父传子)
在父组件中请求导数据通过注册好的子组件在父组件的data中定义好要传的数据在子组件通过props来接收
<template>
<div class="parent">
<h2>{{ msg }}</h2>
<son :fa-msg="msg"></son> <!-- 子组件绑定faMsg变量,注意驼峰-->
</div>
</template>
<script>
import son from './Son' //引入子组件
export default {
name: 'HelloWorld',
data () {
return {
msg: '父组件',
}
},
components:{son},
}
</script>
子组件中用props来接收
<template>
<div class="son">
<p>{{ sonMsg }}</p>
<p>子组件接收到内容:{{ faMsg }}</p>
</div>
</template>
<script>
export default {
name: "son",
data(){
return {
sonMsg:'子组件',
}
},
props:['faMsg'],//接收psMsg值
}
</script>
子传父父组件通过emit来接收(子传父)
子传父在子组件的数据可以在父组件通过e m i t ( ) 方 法 来 实 现 子 传 父 通 过 绑 定 事 件 然 后 及 emit()方法来实现子传父,接受子组件传递过来的参数
<template>
<div class="parent">
<h2>{{ msg }}</h2>
<p>父组件接手到的内容:{{ username }}</p>
<son psMsg="我是你爸爸" @transfer="getUser"></son>
<!-- 监听子组件触发的transfer事件,然后调用getUser方法 -->
</div>
</template>
<script>
import son from './Son'
export default {
name: 'HelloWorld',
data () {
return {
msg: '父组件',
username:'',
}
},
components:{son},
methods:{
getUser(msg){
this.username= msg
}
}
}
</script>
子组件通过$emit触发父组件上的自定义事件
<template>
<div class="son">
<p>{{ sonMsg }}</p>
<p>子组件接收到内容:{{ psMsg }}</p>
<!--<input type="text" v-model="user" @change="setUser">-->
<button @click="setUser">传值</button>
</div>
</template>
<script>
export default {
name: "son",
data(){
return {
sonMsg:'子组件',
user:'子传父的内容'
}
},
props:['psMsg'],
methods:{
setUser:function(){
this.$emit('transfer',this.user)//触发transfer方法,this.user 为向父组件传递的数据
}
}
}
</script>
兄弟
需要在全局注册main.js 初始化 $bus :
window.$bus=new Vue();
组件发送
$bus.$emit("aMsg", '来自A页面的消息');
1
<!-- A.vue -->
<template>
<button @click="sendMsg()">-</button>
</template>
<script>
//import $bus from "../bus.js";
export default {
methods: {
sendMsg() {
$bus.$emit("aMsg", '来自A页面的消息');
}
}
};
</script>
在另一个组件接收
通过$bus.$on("事件名",callback)
来接收
!-- IncrementCount.vue -->
<template>
<p>{{msg}}</p>
</template>
<script>
//import $bus from "../bus.js";
export default {
data(){
return {
msg: ''
}
},
mounted() {
$bus.$on("aMsg", (msg) => {
// A发送来的消息
this.msg = msg;
});
}
};
</script>