一晚上完成0.2.2、0.3.0、0.3.1三個版本的更新,很高興,總結一下
專案地址: 穆音博客
文章首發地址:Vue針對設備調節顯示
Vue中進行優化的方式
總體來說有兩種方法,其一是css的媒體查詢,另一種是vue-mq庫進行對設備斷點,從而區分不同的設備,我這里用的是mq庫進行,以下是使用方法:
匯入mq
使用vue進行匯入
npm install vue-mq
之后修改 main.js中的內容
// main.js
import Vue from 'vue';
import VueMq from 'vue-mq';
Vue.use(VueMq, {
breakpoints: { // 設定設備資訊斷點
mobilePortrait: 320,
mobileLandscape: 480,
tabletPortrait: 768,
tabletLandscape: 1024,
desktop: Infinity,
},
});
配置mq
由于Vue-MQ 庫本身并不提供與 Vuex 的集成,因此無法直接從 Vuex 中獲取設備資訊,我們需要修改store/index.js中的資訊來完成配置
// store.js
const store = new Vuex.Store({
state: {
device: 'desktop', // 初始值為桌面設備
// 其他狀態...
},
mutations: {
updateDevice(state, device) {
state.device = device;
},
// 其他 mutations...
},
// 其他配置項...
});
在根組件中監聽設備變化情況,根據視窗大小完成資訊更新
// App.vue
<template>
<div id="app">
<!-- 頁面內容 -->
</div>
</template>
<script>
export default {
mounted() {
window.addEventListener('resize', this.updateDevice);
this.updateDevice(); // 初始更新設備資訊
},
beforeDestroy() {
window.removeEventListener('resize', this.updateDevice);
},
methods: {
updateDevice() {
const isMobile = window.innerWidth <= 768; // 根據實際情況判斷設備型別
this.$store.commit('updateDevice', isMobile ? 'mobile' : 'desktop');
},
},
};
</script>
頁面內使用
在需要使用的頁面內完成匯入,使用 mapState 輔助函式來獲取設備資訊:
// MyComponent.vue
<template>
<div >
<div v-if="isMobile">
<!-- 移動設備界面 -->
</div>
<div v-else>
<!-- 非移動設備界面 -->
</div>
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
computed: {
...mapState(['device']),
isMobile() {
return this.device === 'mobile';
},
},
};
</script>
<style>
/* 樣式 */
</style>
在上面的示例中,我們使用 mapState 輔助函式來將設備資訊狀態 device 映射到組件的計算屬性中,然后,在模板中使用 isMobile 計算屬性來根據設備資訊判斷是否為移動設備,并相應地渲染不同的界面,
當然,也可以使用之前設定的斷點進行配置,比如
<template>
<div >
<!-- 大屏設備的內容 -->
<div v-if="$mq === 'desktop'">
<!-- 大屏設備特定的內容 -->
</div>
<!-- 移動設備內容 -->
<div v-else-if="$mq === 'mobilePortrait' || $mq === 'mobileLandscape'">
</div>
<!-- 小屏設備的內容 -->
<div v-else>
<!-- 小屏設備特定的內容 -->
</div>
</div>
</template>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/556158.html
標籤:其他
下一篇:返回列表