一、父组件像子组件传值
//parent.vue
<template>
<div>
<child :send-msg-to-child="toChildMsg"></child>
</div>
</template>
<script>
import child from './child.vue';
export default{
name:'parent',
props:[],
data(){
return {
toChildMsg:'about data to child component'
}
},
components:{
child
}
}
</script>
---------------------------------------------------
//child.vue
<template>
<div>{{sendMsgToChild}}</div>
</template>
<script>
export default{
name:'child',
props:['sendMsgToChild'],
data(){
return {
}
},
methods:{
}
}
</script>
二、子组件像父组件传值
child.vue
<template>
<div @click="up">向父组件传递数据</div>
</template>
<script>
import child from './child.vue';
export default{
name:'child',
props:[''],
data(){
return {
}
},
methods:{
up(){
this.$emit('up-up','this is data to parent component')//主动触发upup事件,然后向父组件传递数据
}
}
}
</script>
---------------------------------------------------
parent.vue
<template>
<div>
<child @up-up="getDataFromChild"></child>/*监听子组件触发的upup事件,然后调用getDataFromChild方法获取数据*/
<div>{{getChildMsg}}</div>
</div>
</template>
<script>
import child from './child.vue';
export default{
name:'parent',
props:[],
data(){
return {
getChildMsg:null
}
},
components:{
child
},
methods:{
getDataFromChild(msg){
this.getChildMsg = msg;
}
}
}
</script>
三、
bus.js
import Vue from 'vue'
const bus = new Vue();
export default bus
---------------------------------------------------
component1.vue
<template>
<div>
</div>
</template>
<script>
import bus from '../javascript/bus.js'
export default{
name:'component1',
props:[],
data(){
return {
}
},
components:{
},
methods:{
bus.$emit('change','data to another component')
}
}
</script>
---------------------------------------------------
component2.vue
<template>
<div>
{{getDataFromComponent}}
</div>
</template>
<script>
import bus from '../javascript/bus.js'
export default{
name:'component2',
props:[],
data(){
return {
getDataFromComponent:null
}
},
components:{
},
methods:{
bus.$on('change',msg=>{
this.getDataFromComponent = msg;
})
}
}
</script>