likes
comments
collection
share

vue3+vite+ts+element-plus搭建项目(二)

作者站长头像
站长
· 阅读数 39

上期我们安装了vite,代码管理到git,还有使用eslint验证,接下来我们在项目中安装vuex,router,scss、别名设置等

一、vueRouter

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

1、安装

npm install vue-router@4

2、安装好之后,我们在src目录下新建router目录,在router下新建index.ts文件

index.ts文件内容

import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/home/index.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/index.vue')
  }
]
const router = createRouter({
  history: createWebHashHistory(), // 路由模式
  routes // 路由规则
})

export default router

这块需要注意的是:(1)、history: createWebHashHistory(),调用的是方法,使用的是hash模式(2)、history: createWebHistory(),使用的是h5的history模式(3)、为了规范化typescript开发,增加路由对象RouteRecordRaw类型限制,好处:允许在基础路由里面增加开发者自定义属性,但是有时需要扩展一些字段来定制应用。(4)、因为设置了默认路径是home/index.vue,所以在app.vue中要设置入口vue3+vite+ts+element-plus搭建项目(二)

3、引用在main.ts中引入

import router from './router'

createApp(App).use(router).mount('#app')

二、vuex

官网: https://vuex.vuejs.org/zh/ind...

1、安装

npm install vuex@next --save

2、在src目录下新建store目录,在store目录下新建index.ts,

import { InjectionKey } from 'vue'
import { createStore, useStore as baseUseStore, Store } from 'vuex'

export interface State {
    count: number
  }

export const key: InjectionKey<Store<State>> = Symbol('')
// Create a new store instance.
export const store = createStore<State>({
  state: {
    count: 0
  }
})

// 定义自己的 `useStore` 组合式函数
export function useStore () {
  return baseUseStore(key)
}

3、在main.ts中引入

import store from './store'

createApp(App).use(router).use(store).mount('#app')

4、页面中使用

我们在login/index.vue页面中使用下

vue3+vite+ts+element-plus搭建项目(二)

三、别名配置

官网: https://vitejs.cn/config/#res...

1、配置vite.config.ts

注意:这块的path,ts识别不出来,所以要安装@types/node  

npm i @types/node -D    

vue3+vite+ts+element-plus搭建项目(二)

2、配置tsconfig.json

注意:这块的baseUrl需要配置,否则回报错

vue3+vite+ts+element-plus搭建项目(二)

四、css样式管理

官网: https://vitejs.cn/config/#css...

1、安装scss

npm install -D sass   

2、在src目录下新建styles目录,新建以下文件

common.scss -> 全局公共样式index.scss -> 组织统一导出mixin.scss -> 全局mixintransition.scss -> 全局过度动画样式variables.scss -> 全局sass变量

vue3+vite+ts+element-plus搭建项目(二)

3、在index.scss中引入其他的文件vue3+vite+ts+element-plus搭建项目(二)

4、在main.ts中引入index.scss

import './styles/index.scss'

5、指定传递给 CSS 预处理器的选项,配置如下,在vite.config.ts中

vue3+vite+ts+element-plus搭建项目(二)