更新:
是我太nt了,其实吧设置一下background-size就完事…
.pic1{
background: url('../assets/imgs/wall_index/pic1.png');
background-size: 100% 100%;
}
原文:
父组件:
<template>
<div class="home">
<index-page :Width="windowWidth" :Height="windowHeight" />
</div>
</template>
<script>
import indexPage from "../components/indexPage";
export default {
name: "Home",
components: {
"index-page": indexPage,
},
data() {
return {
windowWidth: document.documentElement.clientWidth, //实时屏幕宽度
windowHeight: document.documentElement.clientHeight, //实时屏幕高度
};
},
// <!--在watch中监听实时宽高-->
watch: {
windowHeight(val) {
let that = this;
console.log("实时屏幕高度:", val, that.windowHeight);
},
windowWidth(val) {
let that = this;
console.log("实时屏幕宽度:", val, that.windowHeight);
},
},
mounted() {
var that = this;
// 传入初始高度
window.onload = () => {
return (() => {
that.windowHeight = document.documentElement.clientHeight; // 高
that.windowWidth = document.documentElement.clientWidth; // 宽
})();
};
// 传入调整高度
// <!--把window.onresize事件挂在到mounted函数上-->
window.onresize = () => {
return (() => {
that.windowHeight = document.documentElement.clientHeight; // 高
that.windowWidth = document.documentElement.clientWidth; // 宽
})();
};
},
methods: {
},
};
</script>
子组件:
<template id="index">
<div>
<div class="back" id="picture1">
<img src="../assets/imgs/indexBackground.png" id="img" />
</div>
</div>
</template>
<script>
export default {
name: "indexPage",
props: {
Width: Number,
Height: Number,
},
created() {},
data() {
return {
// 开始时获取并自适应
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
props: ["Width", "Height"],
};
},
mounted() {
this.change()
},
// 实时监听页面宽高
watch: {
// eslint-disable-next-line no-unused-vars
Width(newWidth, oldWidth) {
this.width = newWidth;
// console.log(newWidth);
this.change();
},
// eslint-disable-next-line no-unused-vars
Height(newHeight, oldHeight) {
this.height = newHeight;
// console.log(newHeight);
this.change();
},
},
methods: {
change() {
var pic = document.getElementById("img");
pic.width = this.width;
pic.height = this.height;
},
},
};
</script>
<style scoped>
.back {
z-index: 1;
position: fixed;
left: 0;
right: 0;
top: 0;
}
</style>