其实就是由 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>