查阅了很多大神们的文章,大致都是只有前部分,后面的如何控制隐藏并没有。
本来是用min-width来限制的 反正有滚动轴,缩再小也不会乱。
后来觉得自适应看起来舒服点,还是研究下自适应吧。做个笔记。
1.首先,一步一步来。
在data里 添加一个变量 screenWidth
export default {
name: "login",
data() {
return {
screenWidth: document.body.clientWidth, //给它赋值个(个人理解为网页的宽度)
}
}
}
2.在页面加载时,挂载这个方法
mounted() {
const that = this;
window.onresize = () => {
return (() => {
window.screenWidth = document.body.clientWidth;
that.screenWidth = window.screenWidth;
})();
};
}
3.最后监听screenWidth值的变化,通过控制台观察screenWidth变化的值
watch: {
screenWidth(val) {
if (!this.timer) { // 为了避免频繁触发resize函数导致页面卡顿,使用定时器
this.screenWidth = val; // 一旦监听到的screenWidth值改变,就将其重新赋给data里的screenWidth
this.timer = true;
let that = this;
setTimeout(function() {
console.log(that.screenWidth); // 打印screenWidth变化的值
that.timer = false;
}, 400);
}
}
}
4.那么当你缩放你所在网页的浏览器时,控制台就会打印出一个个值出来了。
5.有值了 那么怎么通过缩放来控制显示隐藏呢,这里贴个小李子。
<template>
<div>
<p v-show="isshow">随便整了一段文字,啥子都可以,也可以是任意div块,
只要写上v-show, v-if也可以,一般来说, v-if 有更高的切换消耗而 v-show 有更高的初始渲染消耗。
因此,如果需要频繁切换使用 v-show 较好,如果在运行时条件不大可能改变则使用 v-if 较好。
</p>
</div>
</template>
<script>
export default {
data() {
return {
screenWidth: document.body.clientWidth,
isshow:true, //控制上面的isshow,
}
},
methods: {},
mounted() {
const that = this;
window.onresize = () => {
return (() => {
window.screenWidth = document.body.clientWidth;
that.screenWidth = window.screenWidth;
})();
}
},
watch: {
screenWidth(val) {
if (!this.timer) {
this.screenWidth = val;
if (this.screenWidth < 1236) { //这里写了个当值为1236时 就隐藏。
this.isshow = false;
} else {
this.isshow = true;
}
this.timer = true;
let that = this;
setTimeout(function() {
// 打印screenWidth变化的值
console.log(that.screenWidth); //观察完记得注释,不然卡死
that.timer = false;
}, 0);
}
},
}
}
</script>
<style scoped>
</style>
引入组件的话,也一样,
<quanxian v-show="isshow"></quanxian>
总结,可以应用在哪里,如果当页面被缩小到最小时,这时候太多组件的话可能会引起错乱重叠,
不美观,这时候适当的隐藏掉一部分转为按钮来触发其实也不错。
个人理解,个中不足,望指出,做个笔记。