阿里云主机折上折
  • 微信号
Current Site:Index > Vue3 mobile solution

Vue3 mobile solution

Author:Chuan Chen 阅读数:65034人阅读 分类: Vue.js

Vue3 Mobile Adaptation Solutions

Mobile development requires consideration of screen size, device pixel ratio, touch interaction, and other factors. Vue3 offers multiple solutions to address mobile adaptation issues. Below are several mainstream approaches.

Viewport Unit Adaptation

Using vw/vh units can effectively achieve mobile adaptation:

/* Base size for 375px design draft */
html {
  font-size: calc(100vw / 3.75);
}

.box {
  width: 1rem; /* Equivalent to 37.5px in the design draft */
  height: 0.8rem;
  font-size: 0.28rem;
}

With the postcss-px-to-viewport plugin, px units can be automatically converted:

// postcss.config.js
module.exports = {
  plugins: {
    'postcss-px-to-viewport': {
      viewportWidth: 375,
      unitPrecision: 5,
      viewportUnit: 'vw',
      selectorBlackList: [],
      minPixelValue: 1,
      mediaQuery: false
    }
  }
}

Flexible Layout Solution

Flexbox is the most commonly used layout method for mobile:

<template>
  <div class="container">
    <div class="header">Header</div>
    <div class="content">
      <div v-for="item in 5" :key="item" class="item">Item {{item}}</div>
    </div>
    <div class="footer">Footer</div>
  </div>
</template>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.header, .footer {
  flex: 0 0 50px;
}
.content {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
}
.item {
  flex: 0 0 50%;
  height: 100px;
}
</style>

Mobile Component Libraries

Vant is an excellent Vue3 mobile component library:

npm install vant@next

Global import:

import { createApp } from 'vue'
import Vant from 'vant'
import 'vant/lib/index.css'

const app = createApp(App)
app.use(Vant)

Example of on-demand import:

<template>
  <van-button type="primary">Primary Button</van-button>
  <van-cell-group>
    <van-field v-model="value" label="Text" placeholder="Please enter text" />
  </van-cell-group>
</template>

<script setup>
import { ref } from 'vue'
import { Button as VanButton, CellGroup as VanCellGroup, Field as VanField } from 'vant'

const value = ref('')
</script>

Gesture Handling

Vue3 can use @vueuse/gesture for complex gestures:

npm install @vueuse/gesture

Example code:

<template>
  <div 
    ref="boxRef"
    style="width: 100px; height: 100px; background: red"
    @tap="onTap"
    @pan="onPan"
  ></div>
</template>

<script setup>
import { ref } from 'vue'
import { useGesture } from '@vueuse/gesture'

const boxRef = ref(null)
const onTap = () => console.log('tap')
const onPan = (state) => {
  console.log(state.movement) // [x, y] movement distance
}

useGesture({
  onTap,
  onPan
}, {
  target: boxRef,
  eventOptions: { passive: true }
})
</script>

Performance Optimization

Mobile requires special attention to performance optimization:

  1. Lazy loading images
<template>
  <img v-lazy="imgUrl" alt="">
</template>

<script setup>
import { Lazyload } from 'vant'
app.use(Lazyload)
</script>
  1. Virtual lists for long lists
<template>
  <van-list
    v-model:loading="loading"
    :finished="finished"
    @load="onLoad"
  >
    <div v-for="item in list" :key="item">{{ item }}</div>
  </van-list>
</template>
  1. Using keep-alive to cache components
<router-view v-slot="{ Component }">
  <keep-alive>
    <component :is="Component" />
  </keep-alive>
</router-view>

Mobile Debugging

Chrome DevTools remote debugging:

  1. Enable USB debugging on the phone
  2. Visit chrome://inspect in Chrome
  3. Select the device to debug

VConsole solution:

npm install vconsole
import VConsole from 'vconsole'
new VConsole()

PWA Support

Adding PWA support to a Vue3 project:

npm install @vitejs/plugin-pwa

Vite configuration:

import { VitePWA } from 'vite-plugin-pwa'

export default defineConfig({
  plugins: [
    VitePWA({
      includeAssets: ['favicon.ico'],
      manifest: {
        name: 'My App',
        short_name: 'App',
        theme_color: '#ffffff',
        icons: [
          {
            src: 'pwa-192x192.png',
            sizes: '192x192',
            type: 'image/png'
          }
        ]
      }
    })
  ]
})

Cross-Platform Development

Using uni-app for cross-platform development:

npm install -g @vue/cli
vue create -p dcloudio/uni-preset-vue my-project

Example page:

<template>
  <view class="container">
    <text>Hello uni-app</text>
    <button @click="onClick">Click</button>
  </view>
</template>

<script setup>
const onClick = () => {
  uni.showToast({
    title: 'Button clicked'
  })
}
</script>

<style>
.container {
  padding: 20px;
}
</style>

State Management Solution

Pinia for mobile applications:

npm install pinia

Creating a store:

// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  actions: {
    increment() {
      this.count++
    }
  }
})

Using in components:

<template>
  <div>{{ counter.count }}</div>
  <button @click="counter.increment()">+</button>
</template>

<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
</script>

Animation Handling

Vue3 transition animations for mobile:

<template>
  <button @click="show = !show">Toggle</button>
  <transition name="fade">
    <div v-if="show" class="box"></div>
  </transition>
</template>

<style>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
.box {
  width: 100px;
  height: 100px;
  background: red;
}
</style>

Using GSAP for complex animations:

npm install gsap
<script setup>
import { ref, onMounted } from 'vue'
import gsap from 'gsap'

const boxRef = ref(null)
onMounted(() => {
  gsap.to(boxRef.value, {
    x: 100,
    duration: 1,
    repeat: -1,
    yoyo: true
  })
})
</script>

Mobile Routing Handling

Vue Router special handling for mobile:

const router = createRouter({
  history: createWebHashHistory(), // Recommended hash mode for mobile
  routes: [
    {
      path: '/',
      component: Home,
      meta: {
        keepAlive: true // Pages that need caching
      }
    }
  ],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

Page transition animations:

<router-view v-slot="{ Component }">
  <transition name="slide">
    <component :is="Component" />
  </transition>
</router-view>

<style>
.slide-enter-active,
.slide-leave-active {
  transition: transform 0.3s ease;
}
.slide-enter-from {
  transform: translateX(100%);
}
.slide-leave-to {
  transform: translateX(-30%);
}
</style>

Mobile Safe Area Handling

Handling notched screens like iPhone:

.safe-area {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

Using postcss-env plugin for automatic addition:

// postcss.config.js
module.exports = {
  plugins: {
    'postcss-env': {
      browsers: 'last 2 versions'
    }
  }
}

Mobile Theme Switching

Implementing dark mode:

<template>
  <button @click="toggleDark">Toggle Theme</button>
</template>

<script setup>
import { useDark, useToggle } from '@vueuse/core'

const isDark = useDark()
const toggleDark = useToggle(isDark)
</script>

<style>
.dark {
  background: #222;
  color: white;
}
</style>

Mobile Local Storage

Using Pinia for persistent storage:

npm install pinia-plugin-persistedstate

Configuration:

import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

Using in stores:

export const useUserStore = defineStore('user', {
  state: () => ({
    token: ''
  }),
  persist: true
})

Mobile API Request Encapsulation

Encapsulating axios requests:

// utils/request.js
import axios from 'axios'

const service = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 10000
})

service.interceptors.request.use(config => {
  config.headers['X-Token'] = getToken()
  return config
})

service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    return Promise.reject(error)
  }
)

export default service

Using in components:

<script setup>
import request from '@/utils/request'
import { ref } from 'vue'

const list = ref([])
request.get('/api/list').then(res => {
  list.value = res.data
})
</script>

Mobile WebSocket Communication

Implementing real-time communication:

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const messages = ref([])
let socket = null

onMounted(() => {
  socket = new WebSocket('wss://echo.websocket.org')
  
  socket.onopen = () => {
    socket.send('Hello Server!')
  }
  
  socket.onmessage = (e) => {
    messages.value.push(e.data)
  }
})

onUnmounted(() => {
  socket?.close()
})
</script>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:Vue3与Electron集成

下一篇:Vue3微前端方案

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.