小白上路 不喜勿喷哦 也希望大佬可以提出更多的意见
问题描述
- 开发时总会遇见项目不仅要 pc端可用 移动端也可用
- 虽然有更方便的方法 来进行 解决
- 但有的项目主要是做pc端 移动端没有太多具体的 而且 也有可能只有一个页面 会用到这种情况
- 此时在进行 插件的安装 就显得多余且麻烦了
- 故此 可以使用下面这种方法 来进行 解决
代码如下
初始数据
screenWidth: document.body.clientWidth,
isCollapse: false,
结构
<div v-bind:class="classObject">
132
</div>
计算属性
computed: {
classObject: function () {
return {
"text-danger": this.isCollapse,
"text":!this.isCollapse
};
},
},
页面初始化完成后的生命周期
mounted(){
// 监听窗口大小
window.onresize = () => {
return (() => {
this.screenWidth = document.body.clientWidth
})()
}
}
监听当前数据
watch: {
screenWidth(val) {
this.screenWidth = val;
if (this.screenWidth < 768) {
this.isCollapse = true;
} else {
this.isCollapse = false;
}
},
},
样式
.text-danger {
width: 90% !important;
}
.text {
width: auto !important;
}
解析 及 疑问
- 首先获取到初始页面宽度
- 然后 通过初始化页面完成的生命周期钩子函数 来再次确定当前页面的宽度是多少
- 再通过watch 监听 screenWidth 这个属性 并判断页面整体宽度是否小于 我们自己指定的那个值 如果小于 将指定变量进行赋值 反之赋值相反的值
- 最重要的来了 通过上述赋值后的变量 来进行类名的变换
- 我是通过 true 和 false 来进行的
小白上路 不喜勿喷哦 也希望大佬可以提出更多的意见