vue3之vite创建H5项目之3 (Pinia 状态管理的使用与持久化、后端开启一个服务与axios请求数据、proxy代理、axios封装 )

vue3之vite创建H5项目之3 ( )

1:Pinia 状态管理

  • 安装依赖
    • pnpm i pinia-plugin-persistedstate pnpm i pinia

1-1 之 store / index.ts

  • 使用了数据持久化 pinia-plugin-persistedstate
// src/store/index.ts
import {
    
     createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const store = createPinia()
store.use(piniaPluginPersistedstate)
export default store;

1-2 之 main.ts引入

import {
    
     createApp } from 'vue'
import {
    
     createPinia } from 'pinia'

import App from './App.vue'

// 引入 pinia
import store from "./stores/index"

const app = createApp(App)
app.use(store)

1-3 之 stores / user.ts

//src/store/user.ts
import {
    
     defineStore } from 'pinia'
import {
    
     useAppStore } from './app'

export const useUserStore = defineStore({
    
    
  id: 'user',
  state: () => {
    
    
    return {
    
    
      name: '小小亮',
      age: 18
    }
  },
  getters: {
    
    
    fullName: (state) => {
    
    
      return state.name + '叼'
    }
  },
  actions: {
    
    
	// 简单修改一个字段
	updateName(data: any) {
    
    
		this.name = data
	},
	// 修改整个state
    updateStateObj(data: any) {
    
    
      this.$state = data
    //   this.updateAppConfig()
    },
	// 修改age和app配置
	updateAppAndAge(data: any) {
    
    
		this.age = data
		this.updateAppConfig()
	},
    updateAppConfig() {
    
    
      const appStore = useAppStore()
      appStore.setData('app-update')
    }
  },
   // 开启数据缓存
   persist: {
    
    
    key: 'user',
    storage: sessionStorage, // 数据存储位置,默认为 localStorage
    // paths: ['name'], // 用于部分持久化状态的点表示法路径数组,表示不会持久化任何状态(默认为并保留整个状态)
    // overwrite: true
  }
})

1-4 之 stores / app.ts

import {
    
     defineStore } from 'pinia'

export const useAppStore = defineStore({
    
    
	id: 'app',
	state: () => {
    
    
		return {
    
    
			config: 'app配置'
		}
	},
	actions: {
    
    
		setData(data: any) {
    
    
			console.log('setData-app',data)
			this.config = data
		}
	}
})

1-5 调用pinia的方法

<template>
  <div>
	PinaIndex
	<div>
		获取name- {
    
    {
    
     name }} <br/>
		获取age- {
    
    {
    
     age }}<br/>
		获取fullName-计算属性- {
    
    {
    
     userStore.fullName }}<br/>
		获取app的config: {
    
    {
    
     appStore.config }}
	</div>
	<div @click="changeName">
		修改name 
	</div>
	<div @click="changeStateObj">
		修改State对象
	</div>
	<div @click="changeAppAndAge">
		修改Age和app配置
	</div>
	<div @click="goBack">返回</div>
  </div>
</template>

<script setup lang="ts" name='PinaIndex'>
import {
    
     computed } from 'vue'
import {
    
     useRouter } from "vue-router"
const router = useRouter()
import {
    
     useUserStore } from '@/stores/user';
import {
    
     useAppStore } from '@/stores/app';
const userStore = useUserStore()
const appStore = useAppStore()

const name = computed(()=>{
    
    
	return userStore.name
})
const age = computed(()=>{
    
    
	return userStore.age
})
const changeName = ()=> {
    
    
	userStore.updateName('xxxx')
}
const changeStateObj = ()=> {
    
    
	const {
    
     name, age } = userStore.$state
	userStore.updateStateObj({
    
    
		name: name + 1,
		age: age + 1
	})
}
const changeAppAndAge =()=> {
    
    
	const {
    
      age } = userStore.$state
	userStore.updateAppAndAge(age+1)
}


const goBack = ()=>{
    
    
	router.push("/")
}

</script>

<style  lang="scss" scoped>
</style>

3:后端开启一个服务与axios请求数据

3-1 ts-node 文件 后端服务

3-1-1 安装

yarn add ts-node -g
npm init -y
yarn add @types/node -D
yarn add express -S
yarn add @types/express -D
yarn add @types/express -D
yarn add typescript -g

3-1-2 服务的 index.ts

import express,{
    
    Express,Router,Request,Response} from "express"
import axios from "axios"
const cors = require('cors')

const app:Express = express()
const router:Router = express.Router() // 分模块

// 允许所有跨域请求
app.use(cors())

app.use("/api",router) // 

app.get('/list', (req, res) => {
    
    
	res.set('Content-Type', 'text/plain')
	res.send({
    
    
		code:'200',
		data:{
    
    
			msg:'msg'
		}
	})
})

app.listen(8989,()=>{
    
    
  console.log("success server http://localhost:8989");
}) 

3-2 前端使用axios返回接口

import axios from "axios"
onMounted(async ()=>{
    
    
	let {
    
    data} = await axios.get('http://localhost:8989/list')
	console.log('data',data); // {"code": "200", "data": {"msg": "msg"}}
})

4 proxy代理 vite.config.ts

export default ({
    
     command }: ConfigEnv): UserConfigExport =>{
    
    
	return {
    
    
		// 开发环境的 相关配置
		server: {
    
    
		  // 服务配置
		  host: '0.0.0.0',
		  //  port: 5006, // 类型: number 指定服务器端口;
		  //  open: false, // 类型: boolean | string在服务器启动时自动在浏览器中打开应用程序;
		  proxy:{
    
    
			'/api': {
    
    
				target: 'http://XXXX', // 代理的后端接口路径
				changeOrigin: true,
				rewrite: (path) => path.replace(/^\/api/, '')
			  },
		    // 使用 proxy 实例
			// "/api": {
    
    
			// target: "http://XXX",
			// changeOrigin: true,
			// configure: (proxy, options) => {
    
    
			// 	// proxy 是 'http-proxy' 的实例
			// },
			// },
		  }
		},
	}
}

4:封装axios

猜你喜欢

转载自blog.csdn.net/weixin_47409897/article/details/130430612