引用官网的一句话:父子组件的关系可以总结为 prop 向下传递,事件向上传递。父组件通过 prop 给子组件下发数据,子组件通过事件给父组件发送消息,如下图所示:
1,父组件传值给子组件
代码:
<template>
<div style="padding: 20px;">
<span>父组件</span><input type="text" v-model="textInfo" />
<ChildInfo :textInfo="textInfo"></ChildInfo>
</div>
</template>
<script>
import ChildInfo from '../../views/ChildInfo'
export default {
name: 'Home',
components: {ChildInfo},
data () {
return {
textInfo: ''
}
}
}
</script>
<style scoped>
</style>
<template>
<div>
<span>我是子组件:{{textInfo}}</span>
</div>
</template>
<script>
export default {
name: 'ChildInfo',
props: {
textInfo: {
type: String,
required: true
}
}
}
</script>
<style scoped>
</style>
2,子组件传值给父组件
<template>
<div style="padding: 20px;">
<span>父组件</span><input type="text" v-model="textInfo" />
<ChildInfo v-on:funb="funb"></ChildInfo>
</div>
</template>
<script>
import ChildInfo from '../../views/ChildInfo'
export default {
name: 'Home',
components: {ChildInfo},
data () {
return {
textInfo: ''
}
},
methods: {
funb (a) {
this.textInfo = a
}
}
}
</script>
<style scoped>
</style>
<template>
<div>
<span>我是子组件:{{textInfo}}</span><button @click="funa"> 发送数据</button>
</div>
</template>
<script>
export default {
name: 'ChildInfo',
data () {
return {
textInfo: '我是子组件的数据'
}
},
methods: {
funa () {
this.$emit('funb', this.textInfo)
}
}
}
</script>
<style scoped>
</style>
3,非父子组件传值
非父子组件之间传值,需要定义个公共的公共实例文件bus.js,作为中间仓库来传值,不然路由组件之间达不到传值的效果。
bus文件可以理解为组件A和B的父组件,组件A注册一个事件上浮给bus文件,组件B在bus文件下监听事件
?
// bus.js
import Vue from 'vue'
export default new Vue()
<template>
<div>
A组件:
<span>{{elementValue}}</span>
<input type="button" value="点击触发" @click="elementByValue">
</div>
</template>
<script>
import Bus from './bus'
export default {
name: 'ChildInfo',
data () {
return {
elementValue: 10
}
},
methods: {
elementByValue: function () {
Bus.$emit('val', this.elementValue)
}
}
}
</script>
<style scoped>
</style>
<template>
<div>
B组件:
<span>{{elementValue}}</span>
</div>
</template>
<script>
import Bus from './bus'
export default {
name: 'ChildInfo2',
data () {
return {
elementValue: 0
}
},
mounted: function () {
var that = this
// 用$on事件来接收参数
Bus.$on('val', (data) => {
that.elementValue = data
})
},
methods: {
}
}
</script>
<style scoped>
</style>
参考文章:
Vue2.0的三种常用传值方式、父传子、子传父、非父子组件传值_lander_xiong的博客-CSDN博客_vue 父传子
|