Vue兄弟组件之间的传值$on和$emit

其实就是由 vm.$emit 触发$on定义的事件

vm.$on('test', function (msg) {
  console.log(msg)
})
vm.$emit('test', 'hi')
// => "hi"

Bus.js

import Vue from 'vue'
export default new Vue

组件WindowOnresize

<template>
	<div></div>
</template>

<script>
	import Bus from '../api/common/Bus.js';
	
	export default {
	  name: 'WindowOnresize',
	  mounted: function(){
		  // 监听浏览器重置大小事件
		  window.onresize = () => {
			  Bus.$emit("coverInnerWidth", document.body.scrollWidth);
		  }
	  }
	}
</script>

<style>
</style>

组件Cover

<template>
	<div class="box">
		<img :style="{width:imgWidth}" src="/static/img/2020101401.png">
		<h2>根据屏幕大小改变图片的宽度</h2>
	</div>
</template>

<script>
import Bus from '../api/common/Bus.js'
export default{
	name: 'Cover',
	data(){
		return {
			imgWidth: '1024px'
		}
	},
	created(){
		let scrollWidth = document.body.scrollWidth;
		this.imgWidth = scrollWidth+'px';
		Bus.$on('coverInnerWidth', (val) => {
			this.imgWidth = val+'px';
		});
	}
}
</script>

<style scoped>
.box{
	width: 100%;
	position: relative;
	overflow: hidden;
}
.box h2{
	position: absolute;
	top: 50%;
	left: 30%;
	color: white;
}
</style>

App.vue

<template>
  <div id="app">
	<WindowOnresize></WindowOnresize>
	<Cover></Cover>
  </div>
</template>

<script>
import WindowOnresize from './components/WindowOnresize.vue';
import Cover from './components/Cover.vue';

export default {
  name: 'App',
  components: {
	WindowOnresize,
	Cover,
  }
}
</script>

<style>
</style>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值