父组件传值给子组件
子组件传值给父组件
非父子组件间的传值
非父子组件之间传值,需要定义个公共的公共实例文件bus.js,作为中间仓库来传值,不然路由组件之间达不到传值的效果。
公共bus.js
//bus.js
import Vue from 'vue'
export default new Vue()
组件A: child1.vue
<template>
<div>
A组件:
<span>{{elementValue}}</span>
<input type="button" value="点击触发" @click="elementByValue">
</div>
</template>
<script>
// 引入公共的bug,来做为中间传达的工具
import Bus from '../bus/bus.js'
export default {
name: "child1",
data () {
return {
elementValue: 4
}
},
methods: {
elementByValue: function () {
//重点代码:A组件将值传给B组件
Bus.$emit('val', this.elementValue)
}
}
}
</script>
<style scoped>
</style>
B组件:child2.vue
<template>
<div>
B组件:
<input type="button" value="点击触发" @click="getData">
<span>{{name}}</span>
</div>
</template>
<script>
import Bus from './bus.js'
export default {
data () {
return {
name: 0
}
},
mounted: function () {
var vm = this
// 用$on事件来接收A组件传给B组件的参数
Bus.$on('val', (data) => {
console.log(data)
vm.name = data
})
},
methods: {
getData: function () {
this.name++
}
}
}
</script>
参考链接:https://blog.csdn.net/lander_xiong/article/details/79018737