note
技术栈
- vite2
- vue3
- ts
- pinia
- vue-router
- element-plus
- tailwindcss
- ##–react
目标: 管理模板
1、起始,项目搭建!
vue-router yarn add vue-router@4
vue-router ts写法 index
import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
const routes: RouteRecordRaw[] = []
// vite2 新语法特性
const modules = import.meta.globEager('./module/*.ts')
for (const path in modules) {
routes.push(...modules[path].default)
}
const router = createRouter({
history: createWebHashHistory(),
routes: routes,
})
export default router
module 的写法 modlule 模块下的
import type { RouteRecordRaw } from 'vue-router'
const routes: RouteRecordRaw[] = [
{
path: '/admin',
component: () => import('../../pages/Admin.vue'),
},
]
export default routes
pinia 配置 yarn add pinia
全局引入main.ts
import {
createPinia } from 'pinia'
app.use(createPinia())
store 文件夹下实例
import { createPinia } from 'pinia'
import { createPinia } from 'pinia'
import { defineStore } from 'pinia'
const useCountStore = defineStore({
id: 'count',
// arrow function recommended for full type inference
state: () => ({
num: 1,
}),
actions: {
increment() {
this.num++
},
},
})
//store
const instance = useCountStore()
// save
instance.$subscribe((_, state) => {
localStorage.setItem('count-store', JSON.stringify({ ...state }))
})
//getter
let old = localStorage.getItem('count-store')
if (old) {
instance.$state = JSON.parse(old)
}
export default useCountStore
使用
<script lang="ts" setup="">
import useCountStore from '../store/modules/useCountStore'
import { storeToRefs } from 'pinia'
const store = useCountStore()
const refCount = storeToRefs(store)
const { num } = storeToRefs(store)
store.num++
store.increment()
</script>
<template>
<div class="container">
{
{ store.num }}
{
{ refCount.num }}
{
{ num }}
<button @click="store.increment()">点我加一</button>
</div>
</template>
<style lang="scss" scoped></style>
效果
别名的配置 vite alias
这里必须安装一个依赖 yarn add @types/node@16.13.0 -D
注意版本号尽量和自己的node的版本号一致
import {
defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import * as path from 'path'