vite+vue3+ts+pinia/vuex项目搭建

山水有轻音 2022-07-17 PM 741℃ 0条

1、首先

npm init vite@latest
   
或者yarn create vite

再或者 pnpm create vite

安装时选择vue+ts

2、路由的创建与使用 vue3需要4.0版本的路由

1)安装 npm i vue-router

2)创建路由脚本:src目录下>创建router目录>index.ts

编写:/src/router/index.ts

 import { createRouter, RouteRecordRaw, createWebHashHistory } from "vue-router";
 import Home from "../view/login/index.vue";
 const routes = [
         {
             path: "/home",
             component: Home,
             name: "home",
         },
   //   {
   //     path: "/product",
   //     component: () => import("../views/Product.vue"),
   //     name: "product",
   //   },
 ];

 const router = createRouter({
       history: createWebHashHistory(), //哈希值模式
       routes,
 });

 export default router;

3)在main.ts里配置

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
createApp(App).use(router).mount('#app') //use必须要在mount之前

3、安装配置scss/less

npm install sass/less --save
npm install sass/lless-loader --save-dev

vite.config.ts设置

css: {
  // css预处理器
  preprocessorOptions: {
    scss: {
      charset: false,
      //需要在assets下创建对应的文件global.scss
      additionalData: '@import "./src/assets/css/global.scss";',
    },
  },
}

global.scss文件

$main:#ccc;
$c:pink
<template>
  <div class="home">
      <h1 class="h1">全局使用scss</h1>
  </div>
</template>
<style lang="scss" scoped>
.home{
  height: 40px;
  //使用全局变量
  background: $main;
  .h1{
    color:$c
  }
}
</style>

4、设置主题颜色

1)、在css文件下新建color.css

2)、设置变量

:root {
    --bg-color: #10141d; //默认背景颜色
 }
$bg-color: var(--bg-color); //默认背景颜色

3)、vite.config.js配置

import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
 
const pathResolve = (dir) => {
        return resolve(__dirname, ".", dir)
}
 
const alias = {
   '@': pathResolve("src")
}
 
export default ({ command }) => {
        const prodMock = true;
        return {
            base: './',
            resolve: {
                 alias
            },
            server: {
                    port: 3004,
                    host: '0.0.0.0',
                    open: true,
            },
                // 重点⬇️!!!!
            css: {
                    preprocessorOptions: {
                        scss: {
                            additionalData: '@use "@/assets/css/color.scss" as *;'
                        }
                    }
            }
        };
}

5)、css中使用(注意要有lang="scss")

<style lang="scss">
    #app {
          width: 100%;
          height: 100vh;
          background: $bg-color;
    }
</style>

5、引入状态管理pinia/vuex

1)引入使用pinia

 pnpm i pinia --save

2)配置编写

//store/index.ts
import type { App } from 'vue';
import { createPinia } from 'pinia';

const store = createPinia();

export function setupStore(app: App<Element>) {
  app.use(store);
}

export default store

3)在 main.ts 中引入并使用

import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
// 创建vue实例
const app = createApp(App)

// 挂载pinia
app.use(store)
// 挂载实例
app.mount('#app');

4)定义State: 在 src/store 下面创建一个 user.ts

import { defineStore } from 'pinia'
export const useUserStore = defineStore({
       id: 'user', // id必填,且需要唯一
       state: () => {
            return {
                name: '张三'
            }
       },
       actions: {
            updateName(name) {
               this.name = name
            }
       }
 })

5)store/modules/todo/index.ts

export const todoStore = defineStore({
     id: 'todo',
     state: (): ITodoStore => {
           return {
               list: []
           }
      },
      getters: {
           getList(): ITodoItem[] { 
                       return this.list
                 }
            },
            actions: {
                   addTodoItem(item: ITodoItem) { 
                        this.list.unshift(item)
                   },
                   completeTodoItem(item: ITodoItem, isComplete: boolean) { 
                        const index = this.list.indexOf(item)
                        this.list[index].complete = isComplete
                },
                deleteTodoItem(item: ITodoItem) {
                         const index = this.list.indexOf(item)
                         this.list.splice(index, 1)
                }
            }
   })
   export function todoStoreWidthOut() {
           return todoStore(store);
   }

6)使用方式

第一种

<script lang="ts" setup>
import { ITodoItem } from "@/model/todo"
import { todoStoreWidthOut } from "@/store/modules/todo"
const todoStore = todoStoreWidthOut()
const list = todoStore.getList
const onDelete = (item: ITodoItem) => {
  todoStore.deleteTodoItem(item)
}
</script>

第二种

<template>
   <div>{{ userStore.name }}</div>
</template>
<script lang="ts" setup>
import { useUserStore } from '@/store/user'
const userStore = useUserStore()
</script>

修改state

// 1. 直接修改 state (不建议)
userStore.name = '李四'

// 2. 通过 actions 去修改
 <script lang="ts" setup>
import { useUserStore } from '@/store/user'
const userStore = useUserStore()
userStore.updateName('李四')
</script>

7)使用vuex

1、npm i vuex@next --save

2、创建目录/src/store/index.ts

import { createStore } from 'vuex'
// 创建一个新的 store 实例
const store = createStore({
      state () {
            return {
                 count: 0
            }
      },
      mutations: {
            increment (state,payload) {
                 state.count += payload
            }
      },
      getters:{
            totalPrice(state) {
                 return state.count*99.9
            }
      },
      actions:{
            asyncAdd(store,payload){
              setTimeout(()=>{
                      store.commit('increment',payload)
              },1000)
            }
      }
})
export default store

3、在main.ts里输入

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
import store from './store/index'
createApp(App).use(router).use(store).mount('#app') //use必须要在mount之前

4、在页面上使用

<template>
  <div>
          <h1>购物车</h1>
          <h2>商品数量{{store.state.count}}</h2>
          <h2>商品总价{{store.getters.totalPrice}}</h2>
          <button @click="addProd">添加商品数量+2</button>
          <button @click="asyncAddProd">异步添加商品数量+10</button>
  </div>
 </template>
<script setup>
import { useStore } from 'vuex';

let store = useStore()
function addProd(){
  store.commit('increment',2)
}
function asyncAddProd(){
    store.dispatch('asyncAdd',10)
}
</script>    
标签: vite

非特殊说明,本博所有文章均为博主原创。

评论啦~