vue3 + vite4.0 开发项目(PC端和移动端共用一套代码)
做公司官网,为了实现PC端与移动端自适应的问题,决定使用 vue 开发项目,写两套代码,并***采用路由控制,加载PC端代码还是移动端代码,通过屏幕宽度大小来判断加载相应端的代码***。
其中产生的一些问题及难点在这里进行一些记录。
1、创建两套代码的文件夹
创建两套代码的文件夹,其中包含移动端、PC端的所有的内容。
其中的 index.vue 文件是用来存放 的,用于展示路由组件。
2、创建一个文件用于展示两个index.vue组件
创建一个文件用于引入并展示两个index.vue组件,也就是用于判断是pc端、还是移动端的组件进行展示。我是放在了 views 文件夹下,直接创建了一个 index.vue 文件。
其中 devices 是用于获取当前的窗口状态,‘pc’则是PC端,‘mobile’是移动端。
代码如下:
<script setup>
import pc from './pc/index.vue'
import mobile from './mobile/index.vue'
import {
deviceStore } from '@/stores/deviceStore'
const devices = deviceStore()
</script>
<template>
<div>
<pc v-if="devices.device === 'pc'" />
<mobile v-if="devices.device === 'mobile'" />
</div>
</template>
<style lang="scss" scoped>
</style>
3、状态管理 devices
这里主要是使用 pinia 创建了一个状态管理,用于存储,可以全局使用。
代码如下:
// 管理设备数据
import {
defineStore } from 'pinia'
import {
ref } from 'vue'
export const deviceStore = defineStore('devices', () => {
const device = ref('pc') // 默认是PC端,====》 PC端:pc、移动端:mobile
/**
* 切换设备类型
* @param {*} type
*/
const handleToChangeDevice = (type) => {
device.value = type
}
return {
device,
handleToChangeDevice
}
})
4、两套路由
将PC端代码与移动端代码分别写在两套路由表里面,默认的 index.js 中如如这两套路由表,并且默认展示 PC 端的路由。
其中移动端的路由表,大概如下:
export const mobile = [
{
path: '/',
name: 'mobile',
component: () =>