100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 【Vue】组件间传值的三种方式:父传子 子传父 非父子传值

【Vue】组件间传值的三种方式:父传子 子传父 非父子传值

时间:2020-10-17 14:05:13

相关推荐

【Vue】组件间传值的三种方式:父传子 子传父 非父子传值

引用官网的一句话:父子组件的关系可以总结为 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">&nbsp;&nbsp;发送数据</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.jsimport 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>

延申阅读:

vue中非父子组件之间通信除了使用bus总线,也可以使用vuex,两者适用场景不同。

bus适合小项目、数据被更少组件使用的项目,对于中大型项目 数据在很多组件之间使用的情况 bus就不太适用了。bus其实就是一个发布订阅模式,利用vue的自定义事件机制,在触发的地方通过$emit向外发布一个事件,在需要监听的页面,通过$on监听事件。

vuex适用中大型项目、数据在多组件之间公用的情况。

发布订阅模式:

在软件架构中,发布订阅是一种消息范式,消息的发送者(称为发布者)不会将消息直接发送给特定的接收者(称为订阅者)。而是将发布的消息分为不同的类别,无需了解哪些订阅者(如果有的话)可能存在。同样的,订阅者可以表达对一个或多个类别的兴趣,只接收感兴趣的消息,无需了解哪些发布者(如果有的话)存在。

参考文章:

Vue2.0的三种常用传值方式、父传子、子传父、非父子组件传值_lander_xiong的博客-CSDN博客_vue 父传子

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。