Home  >  Article  >  Web Front-end  >  How to configure Vue3+TS+Vant3+Pinia

How to configure Vue3+TS+Vant3+Pinia

WBOY
WBOYforward
2023-05-20 19:57:061476browse

Recommended IDE settings

VS Code Volar

Typing support. Vue in TS imports

because TypeScript cannot handle type information. vue imports, by default they are populated with generic vue component types. If you're only concerned with the template component's prop type, this is fine in most cases. However, if you want to get the actual prop type. vue import, you can enable Volar's takeover mode by following these steps:

1. Run the extension: Show built-in extensions from the command palette of VS Code, look for TypeScript and JavaScript language features, then right-click and Select Disabled (Workspace). Takeover mode is automatically enabled when the default TypeScript extension is disabled.

2. Reload the VS Code window by running Developer:Reload window from the command palette.

Install pnpm

#Lightweight pnpm
Explain a little
The principle of pnpm is that it will not fool-proofly store corresponding copies, but will differential files. Comparison will only add changed files, which is equivalent to the same parts of these multiple projects sharing one version of dependencies.

In this case, the hard disk space can be greatly reduced and the installation speed will be accelerated.

To put it bluntly, it will load much faster than npm.
For example, if you install a dependency, Just use

npm install pnpm -g

and you will find that it is much faster than npm.

pnpm install

1. Install vite

Build vite

yarn create vite

Install dependencies

npm i

Start the project

yarn dev

Select the version of Vue3 TS Can

2. Install pinia

npm add pinia@next

Mount 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')

Introduce Pinia locally

import { defineStore } from 'pinia'

You can see it below A usage example:

  • You can create the store/module/useCountStore.ts file under the corresponding src

  • The specific content is as follows:
    useCountStore.ts

import { defineStore } from 'pinia'

//定义容器
//参数1:容器的id,必须唯一,将来pinia会把所有的容器挂载到根容器
//参数2:选项对象
//返回值是一个函数,调用得到容器实列
export const useMainStore=defineStore('main',{
    //state类似于组件的data,用来存储全局状态的
    //state必须是函数:这样是为了在服务端渲染的时候避免交叉请求导致的数据状态污染
    //必须是箭头函数,这是为了TS更好的类型推导
   state:()=>{
   return{
      count:100,
      foo:'ber',
      arr:[1,2,3]
   }
   },
   //getters 类似于组件的computed,用来封装计算属性,有缓存功能
   //和vuex中的getters没有区别
   getters:{
      // 方式一:这里的state就是上面的state状态对象,使用参数可自动推到出返回值的类型
       count10(state){
       return state.count+20
       },

      //方式二:getters也可使用this
      //直接使用this,ts不会推导出返回值是什么类型,所以要手动标明返回值的类型
/*        count10():number{
          return this.count+20
       }, */


      // 方式三:传递参数,但不使用参数,直接用this,获取值也可,自动推出返回值类型(不推荐使用)
/*       count10(state){
         return this.count+20
      } */
   },
   //类似于组件的methods, 封装业务逻辑,修改state
   actions:{
      //注意不能使用箭头函数定义actions:因为箭头函数绑定外部this,会改变this指向
      //actions就是 通过this返回当前容器实例
      // 这里的actions里的事件接受参数
      // 这里的num:number为自定义参数,需要声明参数类型
      changeState(num:number){
         // this.count++;
         this.count+=num
         this.foo='hello!'
         this.arr.push(4)

         // 同理,actions里也可使用$patch
          this.$patch({})
          this.$patch(state=>{})


         //在此注意:patch和普通多次修改的区别在原理上的区别是
         // 1.涉及到数据响应式和视图更新,多次修改,修改几次视图就更新就更新几次
         // 2.patch 批量修改 视图只更新一次,更有利于性能优化
      }
   }
})
//使用容器中的state
//修改 state
//容器中的actions的使用

After the data is written, you can use it in the component

<template>
  <h4>Pinia基本使用</h4>
  <p>{{mainStore.count}}</p>
  <p>{{mainStore.arr}}</p>
  {{mainStore.count10}}
  <hr />
  <p>解构mainStore后的渲染</p>
  <p>{{count}}</p>
  <p>{{foo}}</p>
  <hr />
  <p>
    <van-button type="success" @click="handleChangeState">修改数据</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);
//可以直接解构mainStore,但是这样是有问题的,这样拿到的数据不是响应式的,是一次性的,之后count和foo的改变这里是不会变的
//Pinia其实就是把state数据都做了reactive处理了
//  const { count,foo}=mainStore

//解决不是响应式的办法 官方的一个api storeToRefs
// storeToRefs的原理是把结构出来的数据做ref响应式代理
const { count, foo } = storeToRefs(mainStore);

const handleChangeState = () => {
  // 数据的修改
  // 方式一:最简单的方式,直接调用修改
  mainStore.count++;

  //方式二:如果要修改多个数据,建议使用$patch 批量更新

  // 方式三:更好的批量更新的函数:$patch是一个函数,这个也是批量更新
  // 这里的state index.ts里的state
  mainStore.$patch((state) => {
    state.count++;
    state.foo = "hello!";
    state.arr.push(4);
  });

  //方式四:逻辑比较多的时候封装到actions中做处理
  mainStore.changeState(10);
};
</script>

3. Install vant3

// 两种都可以
npm i vant
npm i vant@next -s

Install the plug-in

# 通过 npm 安装
npm i unplugin-vue-components -D

# 通过 yarn 安装
yarn add unplugin-vue-components -D

# 通过 pnpm 安装
pnpm add unplugin-vue-components -D

This plug-in can automatically introduce components on demand

Configure the plug-in based on the vite project

Configure in vite.config.ts

import vue from &#39;@vitejs/plugin-vue&#39;;
import Components from &#39;unplugin-vue-components/vite&#39;;
import { VantResolver } from &#39;unplugin-vue-components/resolvers&#39;;

export default {
  plugins: [
    vue(),
    Components({
      resolvers: [VantResolver()],
    }),
  ],
};

Introduce components

Introduce vant component into main.ts

import { createApp } from &#39;vue&#39;;
import { Button } from &#39;vant&#39;;

const app = createApp();
app.use(Button);

4. Install router4

npm install vue-router

How to configure Vue3+TS+Vant3+Pinia

router/index.ts configuration content is as follows:

import { createRouter, createWebHistory,createWebHashHistory, RouteRecordRaw } from &#39;vue-router&#39;
import Home from &#39;../view/Home.vue&#39;;
const routes: Array<RouteRecordRaw> = [
  {
    path: &#39;/&#39;,
    name: &#39;index&#39;,
    component: Home,
  },
]
const router = createRouter({
  history: createWebHashHistory(),
  
 // history: createWebHistory(),
  routes
})
export default router;

main.ts configuration items

import App from &#39;./App.vue&#39;
import router from &#39;./router/index&#39;
app.use(router).mount(&#39;#app&#39;)

App.vue
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-TOITHQne-1658887594763) (./src/assets/image/MDImg/router.png)]

5. Install axios

npm install axios
pnpm install axios

This package is for reference
How to configure Vue3+TS+Vant3+Pinia

How to configure Vue3+TS+Vant3+Pinia
This has been modified and is subject to the code below

 import axios from &#39;axios&#39;

// 创建axios
const service = axios.create({
  // baseURL: &#39;/api&#39;,
  baseURL: &#39;http://xxx.xxx.xx.xxx/&#39;,
  timeout:80000
});

// 添加请求拦截器
service.interceptors.request.use(
  (config:any) => {
    let token:string =&#39;&#39;//此处换成自己获取回来的token,通常存在在cookie或者store里面
    if (token) {
      // 让每个请求携带token-- [&#39;X-Token&#39;]为自定义key 请根据实际情况自行修改
      config.headers[&#39;X-Token&#39;] = 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(&#39;err&#39; + error) // for debug
   if(error.response.status == 403){
     // ElMessage.error(&#39;错了&#39;)
     console.log(&#39;错了&#39;);
     
   }else{
     // ElMessage.error(&#39;服务器请求错误,请稍后再试&#39;)
     console.log(&#39;服务器请求错误,请稍后再试&#39;);
   }
   return Promise.reject(error)
 }
)
export default service;

service.ts
How to configure Vue3+TS+Vant3+Pinia

import {request} from &#39;../request&#39;;
 
// 调用测试
export function getTest(params:any) {
    return request({
      url: &#39;/xxxx&#39;,//此处为自己请求地址
      method: &#39;get&#39;,
      data:params
    })
  }

and then call

// 接口引入地址
import { getTest} from "../utils/api/service";

/* 调用接口 */
       getTest(&#39;放入params参数&#39;).then(response => {
            console.log("结果", response);
          })
          .catch(error => {
            console.log(&#39;获取失败!&#39;)
          });
## on the page #6. Adaptation scheme

postcss-pxtorem plug-in

is used to convert px to rem adaptation (meaning that you only need to fill in the corresponding px value, and you can automatically adapt on the page Configuration, there is no need to manually convert rem.

npm install postcss-pxtorem

Many netizens claim to create a new postcss.config.ts file. Since this writing method is already built into vite, you only need to add it in the vite.config.ts file Just fill in the corresponding configuration.

amfe-flexible plug-in

Set the baseline value

npm i -S amfe-flexible

These two plug-ins are necessary, the configuration items are given below

import { defineConfig } from &#39;vite&#39;
import vue from &#39;@vitejs/plugin-vue&#39;
import Components from &#39;unplugin-vue-components/vite&#39;;
import { VantResolver } from &#39;unplugin-vue-components/resolvers&#39;;
import postcssImport from "postcss-pxtorem"
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    Components({
      resolvers: [VantResolver()],
    }),
    
  ],
  server:{
    host: &#39;0.0.0.0&#39;
  },
  // 适配
  css: {
    postcss: {
      plugins: [
        postcssImport({
          // 这里的rootValue就是你的设计稿大小
          rootValue: 37.5,
          propList: [&#39;*&#39;],
        })
      ]
    }
  }
})

Rendering:


How to configure Vue3+TS+Vant3+Pinia

The above is the detailed content of How to configure Vue3+TS+Vant3+Pinia. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete