vue3+ts项目中router+pinia+scss+unocss+跨域配置

❗️❗️❗️❗️ 写在最前: 本文是根据B站作者 月光分层 视频vue+ts 工程化配置以及作者笔记稍作整理
💖💖作者B站地址https://space.bilibili.com/14110850
💖💖视频教程地址vue+ts 工程化配置
💖💖作者微信:专注前端技术分享,技术讨论加V:18111628033

接上一篇:从零构建vue3+ts+prettier+stylelint+husky+Lint-staged+Commitlint项目

开始配置之前:清空项目文件

一、路由基础配置

官网https://router.vuejs.org/zh/

1. router/index.ts 路由配置

import type { App } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

// 定义路由规则
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    component: () => import('@/views/home/index.vue')
  },
  {
    path: '/about',
    component: () => import('@/views/about/index.vue')
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 为 app 提供路由
export const useRouter = (app: App) => {
  app.use(router)
}

2. main.ts 注册路由

import { createApp } from 'vue'
import App from './App.vue'
import { useRouter } from './router'

const app = createApp(App)

// 使用路由
useRouter(app)

app.mount('#app')

3. App.vue 提供路由出口

<template>
  <div>
    <router-link to="/home">home</router-link>
    <router-link to="/about">about</router-link>
    <router-view></router-view>
  </div>
</template>

<script setup lang="ts"></script>

二、pinia仓库配置

官网https://prazdevs.github.io/pinia-plugin-persistedstate/zh/guide/

1. 持久化配置安装

pnpm i pinia-plugin-persistedstate

pinia-plugin-persistedstate: pinia持久化插件 可以配置储存方式和指定储存内容

2. store/index.ts

// createPinia函数并不需要显示引入 配置有自动导入
// 持久化pinia插件
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
// 创建pinia实例
const pinia = createPinia()
// 使用持久化插件
pinia.use(piniaPluginPersistedstate)
// 函数式注入pinia
const usePinia = (app) => {
  app.use(pinia)
}

export default usePinia

3. 测试仓库 store/app.ts 使用hooks语法

// 引入defineStore 创建pinia仓库
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

// 导出app仓库函数
export const useAppStore = defineStore(
  'app',
  () => {
    // 数据
    const num = ref(20)

    // 改变数据函数
    const addNum = () => {
      num.value += 1
    }

    // 计算熟悉
    const doubleNum = computed(() => num.value * 2)

    // 把仓库数据和函数return出去
    return {
      num,
      addNum,
      doubleNum
    }
  },
  {
    // 持久化配置
    persist: {
      // sessionStorage存储持久化数据
      storage: sessionStorage,
      paths: ['num']
    }
  }
)

4. main.ts 注册仓库

// ...
import usePinia from '@/store'
const app = createApp(App)

// 使用pinia
usePinia(app)

app.mount('#app')

5. 使用仓库测试效果 views/home/index.vue

<template>
  <div>
    <h1>Home</h1>
    <h3>{{ num }}</h3>
    <h3>{{ doubleNum }}</h3>
    <button @click="appStore.addNum()">num+1</button>
  </div>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia'

import { useAppStore } from '@/store/app'

const appStore = useAppStore()

const { num, doubleNum } = storeToRefs(appStore)
</script>

三、配置scss

1. 安装

pnpm add -D scss

2. main.ts 全局引入

// 全局样式引入
import '@/styles/index.scss'

3. vite.config.ts 全局注入样式变量和mixin

// https://vitejs.dev/config/
export default defineConfig({
  // ...
   css: {
    preprocessorOptions: {
      // 全局样式变量预注入
      scss: {
        additionalData: `
          @use "./src/styles/variables.scss" as *;
          @use "./src/styles/mixin.scss" as *;`,
        javascriptEnabled: true
      }
    }
  }
})

四、unocss使用

在这里插入图片描述

官网https://unocss.dev/guide/

1. 安装

pnpm i unocss @iconify-json/ep @unocss/preset-rem-to-px @unocss/transformer-directives -D

unocss 核心库

@iconify-json/epElement Plus 的图标库 https://icones.js.org/ 网站里面找

@unocss/preset-rem-to-pxunocss自带的rem转为px

@unocss/transformer-directives 可以使用@apply @screen theme函数

icon官网https://unocss.dev/presets/icons

博客https://blog.csdn.net/qq_42618566/article/details/135680388

2. vite.config.ts 配置

// unocss vite插件配置
import UnoCSS from 'unocss/vite'

// https://vitejs.dev/config/
export default defineConfig({
  // ...
  plugins: [
    // ...
    UnoCSS(),
  ],
})

3. 在根目录新建uno.config.ts

// uno.config.ts

// 预设rem转px
import presetRemToPx from '@unocss/preset-rem-to-px'
// transformerDirectives 可以使用@apply @screen theme函数
import transformerDirective from '@unocss/transformer-directives'
import {
  defineConfig,
  presetAttributify,
  presetUno,
  transformerVariantGroup,
  presetIcons
} from 'unocss'

export default defineConfig({
  presets: [
    presetAttributify(),
    presetUno(),
    // 现在mt-1会转换为margin-top: 1px
    presetRemToPx({
      baseFontSize: 4
    }),
    // 自动引入图标配置
    presetIcons({
      scale: 1.2,
      warn: true
    })
  ],

  transformers: [transformerVariantGroup(), transformerDirective()],
  //  自定义配置项
  rules: [
    /** 以下官网规则可自定义转换 */
    /* 例如 m-1 转换为 margin:0.25rem */
    // [/^m-(\d+)$/, ([, d]) => ({margin: `${d / 4}rem`})],
    // [/^p-(\d+)$/, match => ({padding: `${match[1] / 4}rem`})],
  ],
  // 自定义属性 一个属性可以对应多个unocss类值
  shortcuts: [
    {
      // 垂直水平居中
      'flex-center': 'flex items-center justify-center',
      // 放在最后
      'flex-end': 'flex items-center justify-end',
      // 垂直居中
      'flex-middle': 'flex items-center',
      // 分开两边
      'flex-between': 'flex items-center justify-between',
      // 竖着居中
      'flex-col-center': 'flex flex-col justify-center'
    }
  ]
})

4. main.ts 全局配置

// eslint-disable-next-line import/no-unresolved
import 'virtual:uno.css' // uno.css
<template>
  <div w200 h200 bg-coolGray flex-center gap-4>
  <div w20 h20 bg-red></div>
  <div w20 h20 bg-red></div>
  <div w20 h20 bg-red></div>
</div>
</template>

5. 图标

i前缀-ep图库名:lock图标名称

<template>
  <div i-ep:ice-drink></div>
  <div i-ep:switch></div>
</template>

五、 跨域配置

官网https://cn.vitejs.dev/config/server-options.html#server-proxy

  • vite.config.ts配置
// https://vitejs.dev/config/
export default defineConfig({
  server: {
    // 监听所有公共ip
    // host: '0.0.0.0', // 可在package.json中开启: "dev": "vite --host" 代替
    cors: true,
    port: 3300,
    proxy: {
      // 前缀
      '/api': {
        target: 'http://www.example.com',
        changeOrigin: true,
        // 前缀重写
        rewrite: (path: string) => path.replace(/^\/api/, '/api')
      }
    }
  }
})
  • 13
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值