对vue组件之间的传值的理解

vue的组件传值可以分为三种,一种是父组件传子组件,使用的是props 例:

定义两个组件 一个是父组件 index.vue 一个是子组件 child.vue

index.vue的代码如下:

<template>
<div>
<div>我是父组件</div>
<child :message="name"></child>
</div>
</template>
<script>

import child from '../components/footer/footer'
export default {
data() {
return {
msg: '',
name:'小张'
}
},
components: {
'child':child
},
methods:{
}

}
</script>

子组件的代码如下:
<template>
<div>
<div style="text-align: left;">我是子组件的:{{message}}</div>
</div>
</template>
<script>
export default {
data() {
return {
msg: '',
isShow:true
}
},
mounted(){
console.log(this.message);
console.log(this.type);
},
props: ['type',"message"]

}
</script>

以上是父传子。
如果是子组件传父组件,如下
子组件代码
<template>
<div>
<div style="text-align: left;">我是子组件<a @click="toParent">点击我向父组件传值</a></div>
</div>
</template>
<script>
export default {
data() {
return {
msg: '',
isShow:true
}
},
mounted(){
},
methods:{
toParent(){
this.$emit('fromChild',this.isShow)
}
}

}
</script>

父组件代码
<template>
<div>
<div>我是父组件</div>
{{msg}}
<child @fromChild="receiveChild"></child>
</div>
</template>
<script>
import child from '../components/child'
export default {
data(){
return {
msg:'1'
}
},
components:{
'child':child
},
methods:{
receiveChild(e){
console.log(e);
this.msg=e;
}
}
}

</script>
第三种是组件与组件之间的传值:原理是通过一个中央数据中线,就是一个中间组件来进行传递,如在main.js里定义了一个 import Vue from 'vue' ; let eventHub=new Vue();

通过这个进行触发: this.$root.eventHub.$emit('toChild1',this.msg);通过这个进行接收
mounted(){
this.$root.eventHub.$on('toChild1',(val)=>{
console.info(val)
})
}
有三个组件 一个是 父组件 index.vue 还有一个 child.vue 以及child1.vue
index的代码如下:

<template>
<div>
<div>我是父组件</div>
{{msg}}
<child @fromChild="receiveChild"></child>
<child1></child1>
</div>
</template>
<script>
import child from '../components/footer/footer'
import child1 from '../components/footer/footer1'
import Vue from 'vue'

export default {
data(){
return {
msg:'1'
}
},
components:{
'child':child,
'child1':child1

},
methods:{
receiveChild(e){
console.log(e);
this.msg=e;
}
}
}

</script>

child的代码如下:
<template>
<div>
<!--<div style="text-align: left;">我是子组件<a @click="toParent">点击我向父组件传值</a></div>-->
<div>传值到另外一个非父子组件 <a @click="toChild1">点击我</a></div>
</div>
</template>
<script>
import Vue from 'vue'
export default {
data() {
return {
msg: '',
isShow:true
}
},
mounted(){
},
methods:{
toParent(){
this.$emit('fromChild',this.isShow)
},
toChild1() {
this.$root.eventHub.$emit('toChild1', this.isShow); // 传输点击的目标元素
}
}

}
</script>
<style scoped>

</style>

child1的代码如下:
<template>
<div>
<div>
我想在这个组件上接受到 另外一个非父子组件的值
</div>
</div>
</template>
<script>
export default {
data() {
return {
msg: ''
}
},
mounted(){
this.$root.eventHub.$on('toChild1',(val)=>{
console.info(val)
})
},
methods: {

}

}
</script>
<style scoped>

</style>
要在main.js定义eventHub。





 

---恢复内容结束---

猜你喜欢

转载自www.cnblogs.com/weining521/p/9205093.html