Vue3+TS+Vant3+Pinia(H5端)配置教程詳解
該模板將幫助您開始使用Vue 3、Vite3.0中的TypeScript以及Pinia、Vant3進(jìn)行開發(fā)。該模板使用Vue3,請查看文檔了解更多教程。
推薦的IDE設(shè)置
VS Code + Volar
鍵入支持。TS中的vue導(dǎo)入
因為TypeScript無法處理的類型信息。vue導(dǎo)入,默認(rèn)情況下,它們填充為通用vue組件類型。在大多數(shù)情況下,如果您不真正關(guān)心模板之外的組件道具類型,那么這很好。然而,如果你想得到實際的道具類型。vue導(dǎo)入,您可以通過以下步驟啟用Volar的接管模式:
1.運(yùn)行擴(kuò)展:從VS代碼的命令調(diào)色板中顯示內(nèi)置擴(kuò)展,查找TypeScript和JavaScript語言功能,然后右鍵單擊并選擇禁用(工作區(qū))。默認(rèn)情況下,如果禁用默認(rèn)的TypeScript擴(kuò)展,則接管模式將自動啟用。
2.通過從命令調(diào)色板運(yùn)行Developer:Reload window重新加載VS代碼窗口。
安裝pnpm
如果想一步一步安裝可以參考以下文檔,都有詳細(xì)的解釋
#輕量級pnpm
稍微解釋一下
pnpm的原理在于不會傻瓜式的無腦存儲相應(yīng)的副本,而是進(jìn)行差異文件的比對,只會增加變化了的文件,相當(dāng)于這些多個項目相同的部分都共享了一個版本的依賴。
這樣的話,硬盤空間可以得到大量的縮減,同時加快了安裝速度??磦€圖
說白了就是會比npm加載速度快很多
比如說安裝一個依賴,就可以使用
npm install pnpm -g
你會發(fā)現(xiàn)比npm快的多的多。
pnpm install
一、安裝vite
搭建vite
yarn create vite
安裝依賴
npm i
啟動項目
yarn dev
選擇Vue3+TS的版本即可
二、安裝pinia
npm add pinia@next
掛載Pinia
main.ts
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import {createPinia} from 'pinia'
const pinia = createPinia()
const app = createApp(App)
// 掛載到 Vue 根實例
app.use(pinia)
createApp(App).mount('#app')
局部引入Pinia
import { defineStore } from 'pinia'
下面可以看個使用例子:
- 可以在對應(yīng)的src下創(chuàng)建store/module/useCountStore.ts文件
- 具體內(nèi)容如下:
useCountStore.ts
import { defineStore } from 'pinia'
//定義容器
//參數(shù)1:容器的id,必須唯一,將來pinia會把所有的容器掛載到根容器
//參數(shù)2:選項對象
//返回值是一個函數(shù),調(diào)用得到容器實列
export const useMainStore=defineStore('main',{
//state類似于組件的data,用來存儲全局狀態(tài)的
//state必須是函數(shù):這樣是為了在服務(wù)端渲染的時候避免交叉請求導(dǎo)致的數(shù)據(jù)狀態(tài)污染
//必須是箭頭函數(shù),這是為了TS更好的類型推導(dǎo)
state:()=>{
return{
count:100,
foo:'ber',
arr:[1,2,3]
}
},
//getters 類似于組件的computed,用來封裝計算屬性,有緩存功能
//和vuex中的getters沒有區(qū)別
getters:{
// 方式一:這里的state就是上面的state狀態(tài)對象,使用參數(shù)可自動推到出返回值的類型
count10(state){
return state.count+20
},
//方式二:getters也可使用this
//直接使用this,ts不會推導(dǎo)出返回值是什么類型,所以要手動標(biāo)明返回值的類型
/* count10():number{
return this.count+20
}, */
// 方式三:傳遞參數(shù),但不使用參數(shù),直接用this,獲取值也可,自動推出返回值類型(不推薦使用)
/* count10(state){
return this.count+20
} */
},
//類似于組件的methods, 封裝業(yè)務(wù)邏輯,修改state
actions:{
//注意不能使用箭頭函數(shù)定義actions:因為箭頭函數(shù)綁定外部this,會改變this指向
//actions就是 通過this返回當(dāng)前容器實例
// 這里的actions里的事件接受參數(shù)
// 這里的num:number為自定義參數(shù),需要聲明參數(shù)類型
changeState(num:number){
// this.count++;
this.count+=num
this.foo='hello!'
this.arr.push(4)
// 同理,actions里也可使用$patch
this.$patch({})
this.$patch(state=>{})
//在此注意:patch和普通多次修改的區(qū)別在原理上的區(qū)別是
// 1.涉及到數(shù)據(jù)響應(yīng)式和視圖更新,多次修改,修改幾次視圖就更新就更新幾次
// 2.patch 批量修改 視圖只更新一次,更有利于性能優(yōu)化
}
}
})
//使用容器中的state
//修改 state
//容器中的actions的使用
數(shù)據(jù)寫好之后在組件中使用即可
<template>
<h3>Pinia基本使用</h3>
<p>{{mainStore.count}}</p>
<p>{{mainStore.arr}}</p>
{{mainStore.count10}}
<hr />
<p>解構(gòu)mainStore后的渲染</p>
<p>{{count}}</p>
<p>{{foo}}</p>
<hr />
<p>
<van-button type="success" @click="handleChangeState">修改數(shù)據(jù)</van-button>
</p>
</template>
<script lang="ts" setup>
import { useMainStore } from "../../store/module/useCountStore";
import { storeToRefs } from "pinia";
const mainStore = useMainStore();
console.log(mainStore.count);
//可以直接解構(gòu)mainStore,但是這樣是有問題的,這樣拿到的數(shù)據(jù)不是響應(yīng)式的,是一次性的,之后count和foo的改變這里是不會變的
//Pinia其實就是把state數(shù)據(jù)都做了reactive處理了
// const { count,foo}=mainStore
//解決不是響應(yīng)式的辦法 官方的一個api storeToRefs
// storeToRefs的原理是把結(jié)構(gòu)出來的數(shù)據(jù)做ref響應(yīng)式代理
const { count, foo } = storeToRefs(mainStore);
const handleChangeState = () => {
// 數(shù)據(jù)的修改
// 方式一:最簡單的方式,直接調(diào)用修改
mainStore.count++;
//方式二:如果要修改多個數(shù)據(jù),建議使用$patch 批量更新
// 方式三:更好的批量更新的函數(shù):$patch是一個函數(shù),這個也是批量更新
// 這里的state index.ts里的state
mainStore.$patch((state) => {
state.count++;
state.foo = "hello!";
state.arr.push(4);
});
//方式四:邏輯比較多的時候封裝到actions中做處理
mainStore.changeState(10);
};
</script>
寫完后就可以使用了,具體使用教程可以參考官方文檔Pinia官網(wǎng)
三、安裝vant3
// 兩種都可以 npm i vant npm i vant@next -s
安裝插件
# 通過 npm 安裝 npm i unplugin-vue-components -D # 通過 yarn 安裝 yarn add unplugin-vue-components -D # 通過 pnpm 安裝 pnpm add unplugin-vue-components -D
這個插件可以自動按需引入組件
基于vite項目配置插件
在vite.config.ts中配置
import vue from '@vitejs/plugin-vue';
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from 'unplugin-vue-components/resolvers';
export default {
plugins: [
vue(),
Components({
resolvers: [VantResolver()],
}),
],
};
引入組件
在mian.ts中引入vant組件
import { createApp } from 'vue';
import { Button } from 'vant';
const app = createApp();
app.use(Button);
四、安裝router4
npm install vue-router

router/index.ts配置內(nèi)容如下:
import { createRouter, createWebHistory,createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Home from '../view/Home.vue';
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'index',
component: Home,
},
]
const router = createRouter({
history: createWebHashHistory(),
// history: createWebHistory(),
routes
})
export default router;
main.ts配置項
import App from './App.vue'
import router from './router/index'
app.use(router).mount('#app')
App.vue
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-TOITHQne-1658887594763)(./src/assets/image/MDImg/router.png)]
五、安裝axios
npm install axios pnpm install axios
這個封裝可供參考

此處經(jīng)過修改,以下方代碼為準(zhǔn)
import axios from 'axios'
// 創(chuàng)建axios
const service = axios.create({
// baseURL: '/api',
baseURL: 'http://xxx.xxx.xx.xxx/',
timeout:80000
});
// 添加請求攔截器
service.interceptors.request.use(
(config:any) => {
let token:string =''//此處換成自己獲取回來的token,通常存在在cookie或者store里面
if (token) {
// 讓每個請求攜帶token-- ['X-Token']為自定義key 請根據(jù)實際情況自行修改
config.headers['X-Token'] = token
config.headers.Authorization = + token
}
return config
},
error => {
// Do something with request error
console.log("出錯啦", error) // for debug
Promise.reject(error)
}
)
service.interceptors.response.use(
(response:any) => {
return response.data
}, /* */
error => {
console.log('err' + error) // for debug
if(error.response.status == 403){
// ElMessage.error('錯了')
console.log('錯了');
}else{
// ElMessage.error('服務(wù)器請求錯誤,請稍后再試')
console.log('服務(wù)器請求錯誤,請稍后再試');
}
return Promise.reject(error)
}
)
export default service;
service.ts
import {request} from '../request';
// 調(diào)用測試
export function getTest(params:any) {
return request({
url: '/xxxx',//此處為自己請求地址
method: 'get',
data:params
})
}
之后在頁面中調(diào)用
// 接口引入地址
import { getTest} from "../utils/api/service";
/* 調(diào)用接口 */
getTest('放入params參數(shù)').then(response => {
console.log("結(jié)果", response);
})
.catch(error => {
console.log('獲取失敗!')
});
六、適配方案
postcss-pxtorem插件
用來將px轉(zhuǎn)換成rem適配(意思就是你只需要填寫對應(yīng)的px值,就可以在頁面上自動適配,不需要自己手動轉(zhuǎn)rem。
npm install postcss-pxtorem
網(wǎng)上有很多人說這個需要新建什么postcss.config.ts文件。在vite中是自帶了這種寫法,所以只需要直接在vite.config.ts中填寫相關(guān)配置就可以了。
amfe-flexible插件
設(shè)置基準(zhǔn)值
npm i -S amfe-flexible
這兩個插件是必備的,下面給出配置項
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from 'unplugin-vue-components/resolvers';
import postcssImport from "postcss-pxtorem"
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
Components({
resolvers: [VantResolver()],
}),
],
server:{
host: '0.0.0.0'
},
// 適配
css: {
postcss: {
plugins: [
postcssImport({
// 這里的rootValue就是你的設(shè)計稿大小
rootValue: 37.5,
propList: ['*'],
})
]
}
}
})
效果圖:
到此這篇關(guān)于Vue3+Vant3+Pinia(H5端)配置教程詳解的文章就介紹到這了,更多相關(guān)Vue3+Vant3+Pinia(H5端)配置教程內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3+Element?Plus動態(tài)表單實現(xiàn)
本文主要介紹了Vue3+Element?Plus動態(tài)表單實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-05-05
關(guān)于vue中根據(jù)用戶權(quán)限動態(tài)添加路由的問題
每次路由發(fā)生變化時都需要調(diào)用一次路由守衛(wèi),并且store中的數(shù)據(jù)會在每次刷新的時候清空,因此需要判斷store中是否有添加的動態(tài)路由,本文給大家分享vue中根據(jù)用戶權(quán)限動態(tài)添加路由的問題,感興趣的朋友一起看看吧2021-11-11
element-ui?table使用type='selection'復(fù)選框全禁用(全選禁用)詳解
element-ui中的table的多選很好用,但是如果其中某一項禁止選擇,該怎樣操作呢,下面這篇文章主要給大家介紹了關(guān)于element-ui?table使用type='selection'復(fù)選框全禁用(全選禁用)的相關(guān)資料,需要的朋友可以參考下2023-01-01
mpvue中配置vuex并持久化到本地Storage圖文教程解析
這篇文章主要介紹了mpvue中配置vuex并持久化到本地Storage的教程詳解,# 配置vuex和在vue中相同,只是mpvue有一個坑,就是不能直接在new Vue的時候傳入store。本文分步驟給大家介紹的非常詳細(xì),需要的朋友參考下吧2018-03-03
Vue的watch和computed方法的使用及區(qū)別介紹
Vue的watch屬性可以用來監(jiān)聽data屬性中數(shù)據(jù)的變化。這篇文章主要介紹了Vue的watch和computed方法的使用及區(qū)別,需要的朋友可以參考下2018-09-09
vue項目中如何使用TypeScript相關(guān)配置
這篇文章主要給大家介紹了關(guān)于vue項目中如何使用TypeScript相關(guān)配置的相關(guān)資料,typescript在開發(fā)過程中廣泛被應(yīng)用,在這里總結(jié)下項目中ts的應(yīng)用,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-11-11

