uniapp vuex和pinia使用

二者都为vue的状态存储插件,pinia被誉为vuex的下一代状态存储

实例 简单登录和退出效果图

在这里插入图片描述

1新建uniapp项目

详细文档看官方的uniapp新建项目链接

2安装pinia

如果新建项目,先初始化一下

npm init -y
npm install pinia --save

3新建pinia store目录,并创建相关文件

名字自己定我的是pinia-store,在目录下新建index.js和login.js,代码如下
index.js

import { createPinia } from 'pinia'

const store = createPinia()

export default store

login.js

import { defineStore } from 'pinia'

export const useloginStore = defineStore({
  id: 'login', // id必填,且需要唯一
  state: () => {
    return {
      userName: uni.getStorageSync('userName') ? uni.getStorageSync('userName') : '未登录'
    }
  },
  // actions 用来修改 state
    actions: {
      login(userName) {
      	uni.setStorageSync('userName', userName)
      	this.userName = userName
      },
      logout() {
      	uni.clearStorage()
      	this.userName = '已退出登录'
      }
    }
})

对比vuex的store/index.js
注意:如果只使用pinia这段代码可以没有

import { createStore } from "vuex"

const store = createStore({
	state: {
		"userName": uni.getStorageSync('userName') ? uni.getStorageSync('userName') : '未登录'
	},
	mutations: {
		MLOGIN(state, userName) {
			uni.setStorageSync('userName', userName)
			state.userName = userName
		},
		MLOGOUT(state) {
			uni.clearStorage()
			state.userName = '已退出登录'
		}
	},
	actions: {
		login(context, userName) {
			context.commit('MLOGIN', userName)
		},
		logout(context) {
			context.commit('MLOGOUT')
		}
	}
})

export default store

4mian.js 修改

引入vuex和pinia的文件并use

import App from './App'

// #ifndef VUE3
import Vue from 'vue'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
	...App,
})
app.$mount()
// #endif

// #ifdef VUE3
import {
	createSSRApp
} from 'vue'
// vuex
import store from './store'
// pinia
import pstore from './pinia-store'
export function createApp() {
	const app = createSSRApp(App)
	app.use(pstore)
	app.use(store)
	return {
		app
	}
}
// #endif

5主页面逻辑代码

在uniapp创建页面名字任意,我的是me.vue
注意:注释部分为vuex代码

<template>
	<view>
		<view>
			<button type="primary" @click="login('刘大根')">登录</button>
			<button type="default" @click="logout">退出</button>
		</view>
		<!-- <view>{{userName}}</view> -->
		<view>{{loginStore.userName}}</view>
	</view>
</template>

<script>
	// import store from '@/store/index.js'
	// import {
	// 	mapActions,
	// 	mapState
	// } from 'vuex'
import { useloginStore } from '@/pinia-store/login'
const loginStore = useloginStore()

	export default {
		data() {
			return {
				loginStore:loginStore
			}
		},
		computed: {
			// ...mapState(['userName'])			
		},
		methods: {
			// ...mapActions(['login','logout'])
			login(userName){
				loginStore.login(userName)
			},
			logout(){
				loginStore.logout()
			}
			
		}
	}
</script>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐