Vue中A页面引用B页面,并且互相传参

场景描述:开发A页面过程中,有个弹框,弹框功能内容和B页面一致;引入B页面时,需要从A传参给B,弹框任务执行完后,需要将结果返回给A。
在这里插入图片描述
A页面Vue代码为:

<template>
	<div class="app-container" style="padding: 10px;">
        <el-container>
    		<el-main>
    			<span>这是A页面</span>
                 <!-- 弹框引入B页面 -->
                <el-dialog :close-on-click-modal="false" append-to-body width="60%" title="弹框引入B页面" 						:visible.sync="bPage_view">
                    <!-- BPageVue在components定义的B页面组件 -->
                    <!-- toBParams是A向B传的参数对象,在data里定义 -->
                    <!-- emitToParent是B返回的结果,与B页面的保持一至 -->
                  <BPageVue :optionsData='toBParams' @emitToParent='getBRes'></BPageVue>
                </el-dialog>
    		</el-main>
    	</el-container>
    </div>
</template>

<script>
	import bPage from 'xxx/xxx/b.vue'
    
    export default {
        components: {
            "BPage": bPage
        },
        data: {
            return: {
                bPage_view: false,
                toBParams: { paramsOne: '1', paramsTwo: '2' }, //A页面向B页面传递的参数
                BAnswer: ''
            }
        },
        methods: {
            // 读取B页面返回的结果
            getBRes(data): {
            	this.BAnswer = data
        	}
        }
    }
</script>

B页面Vue代码为:

<template>
	<div class="app-container" style="padding: 10px;">
        <el-container>
    		<el-main>
    			<span>这是B页面</span>
                <button @click='toParentRes'>点击向A页面返回结果</button>
    		</el-main>
    	</el-container>
    </div>
</template>

<script>
    export default {
        // props,接收从A传递来的参数对象,optionsData和A页面中的保持一直
        props: {
          optionsData: {
            type: Object
          }
        },
        data: {
            return: {
                paramsOne: '',
                paramsTwo: '',
                BRes: 'B页面的结果'
            }
        },
        methods: {
			// 初始化参数
            initData: {
                if (this.isNull(this.optionsData.paramsOne)) {
                  this.paramsOne = this.optionsData.paramsOne
                }
                if (this.isNull(this.optionsData.paramsTwo)) {
                  this.paramsTwo = this.optionsData.paramsTwo
                }
            },
            // 向A页面返回结果
            toParentRes: {
              this.$emit('emitToParent', this.BRes)
            }
        }
    }
</script>

总结:

1、A页面想要引用B页面,则在A页面把B页面变成组件(components)使用;
2、A向B传参数,A页面在使用组件的时候传递参数(:xx=‘yy’),B页面用props接收参数对象;
3、B向A返回结果,用$emit返回结果。A页面在使用组件的时候@xxx接收结果

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值