vue两个独立的组件之间的传值通信

我们想要监听组件A里面data里的某个值,然后传给组件B使用,还要达到动态改变组件B里面data里的某个值

目录下新建一个公共文件 pubilc.js

import Vue from 'vue'
export default new Vue()

在组件A:save.vue中导入pubilc.js

<template>
	<div>
		<i class="iconfont icon-camera" @click="testA">
	<div>
</template>

<script>
import Public from './public.js'
export default {
	name: "save",
	data() {
		return {
			data_1: 0,
		};
	},
	components: {},
	created() {},
	methods: {
		testA() {
			this.data_1 += 1
			Public.$emit('transportData', this.data_1); //监听data_1的变化
		},
	}
	
};
</script>

在组件B:show.vue中导入pubilc.js

<template>
	<div>
		<i class="iconfont icon-layer" @click="testB">
	<div>
</template>

<script>
import Public from './public.js'
export default {
	name: "show",
	data() {
		return {
			data_1: 0,
			data_2: 0,
		};
	},
	components: {},
	created() {
		Public.$on('transportData', val => {  //接收save.vue中传过来的data_1的值
            this.data_1 = val;
        });
	},
	methods: {
		testB() {
			this.data_2 = this.data_1 + 100;
			console.log(this.data_2);
		},
	}
	
};
</script>

你可能感兴趣的:(前端)