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。
---恢復內容結束---