记录三种Vue.js组件参数传递;
1.子组件向父组件传递参数;
子组件A:
<template>
<div class="childA-wrapper">
子组件A
</div>
</template>
<script>
export default {
data() {
return {
childA: '我是组件A传过来的值'
}
},
created: function() {},
mounted() {
this.sendDataParent()
},
methods: {
sendDataParent() {
// getChildDataA是在父组件on监听的方法
// 第二个参数this.childA是需要传的值
this.$emit('getChildDataA', this.childA)
}
}
}
</script>
子组件B:
<template>
<div class="childB-wrapper">
子组件B
</div>
</template>
<script>
export default {
data() {
return {
childB:'我是组件B传过来的值'
}
},
created:function() {
},
mounted(){
this.sendDataParent()
},
methods: {
sendDataParent() {
// getChildDataB是在父组件on监听的方法
// 第二个参数this.childB是需要传的值
this.$emit('getChildDataB', this.childB)
}
}
}
</script>
父组件:
<template>
<div>
<v-childA v-on:getChildDataA="getChildDataA"></v-childA>
<v-childB v-on:getChildDataB="getChildDataB"></v-childB>
<div>获取组件A传过来的值:{{childAValue}}</div>
<div>获取组件B传过来的值:{{childBValue}}</div>
</div>
</template>
<script>
import childA from '@/components/childA.vue'
import childB from '@/components/childB.vue'
export default {
data() {
return {
childAValue:'',
childBValue:'',
}
},
methods: {
getChildDataA(childA){
console.log(childA)
this.childAValue=childA
},
getChildDataB(childB){
console.log(childB)
this.childBValue=childB
}
},
components: { 'v-childA': childA, 'v-childB': childB}
}
</script>
二、父组件向子组件传递参数
父组件:
<template>
<div>
<v-childA></v-childA>
<v-childB :sendBData="sendB"></v-childB>
</div>
</template>
<script>
import childA from '@/components/childA.vue'
import childB from '@/components/childB.vue'
export default {
data() {
return {
sendB:'父组件向B组件传递的参数'
}
},
methods: {
},
components: { 'v-childA': childA, 'v-childB': childB}
}
</script>
子组件B:
<template>
<div class="childB-wrapper">
子组件B:{{sendBData}}
</div>
</template>
<script>
export default {
data() {
return {}
},
created: function() {},
mounted() {},
methods: {},
props: {
sendBData: String,
required: true
}
}
</script>
三、非父子组件进行传值;
bus.js
import Vue from 'vue'
export default new Vue()
组件childB:
<template>
<div class="childB-wrapper">
</div>
</template>
<script>
import Bus from '@/common/bus.js'
export default {
data() {
return {
childB: '我是组件B的内容'
}
},
created: function() {},
mounted() {
this.elementByValue()
},
methods: {
elementByValue: function () {
Bus.$emit('val', this.childB)
}
}
}
</script>
组件childA:
<template>
<div class="childA-wrapper">
A组件:<span>{{childB}}</span>
</div>
</template>
<script>
import Bus from '@/common/bus.js'
export default {
data() {
return {
childB: ''
}
},
created: function() {},
mounted() {
var that = this
// 用$on事件来接收参数
Bus.$on('val', (data) => {
console.log(data)
that.childB = data
})
}
}
</script>
转载于:https://www.jianshu.com/p/be5d9c6596f9