vue之组件之间的传值

1、父组件向子组件传值
//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>
2、子组件向父组件传值
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>
3、非父子组件之间的传值
bus.js

import Vue from 'vue'
const bus = new Vue();
export default bus
---------------------------------------------------
component1.vue

<template>
<div>
<div @click="toCompontent2">非父子组件传递</div>
</div>
</template>
<script>
import bus from '../javascript/bus.js'
export default{
name:'component1',
props:[],
data(){
return {

}
},
components:{

},
methods:{
toCompontent2(){
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:{

},
mounted:{
bus.$on('change',msg=>{
this.getDataFromComponent = msg;
})
}
}

</script>