文章目录
vuex和pinia使用
二者都为vue小程序开发定制的状态存储插件,被誉为vuex小程序开发定制的下一代状态存储
实例 简单登录和退出效果图
1新建
详细文档看官方的
2安装pinia
如果新建项目,先初始化一下
npm init -y
- 1
npm install pinia --save
- 1
3新建pinia store目录,并创建相关文件
名字自己定我的是pinia-store,在目录下新建index.js和login.js,代码如下
index.js
import { createPinia } from 'pinia'const store = createPinia()export default store
- 1
- 2
- 3
- 4
- 5
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 = '已退出登录' } }})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
对比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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
4mian.js 修改
引入vuex和pinia的文件并use
import App from './App'// #ifndef VUE3import Vue from 'vue'Vue.config.productionTip = falseApp.mpType = 'app'const app = new Vue({ ...App,})app.$mount()// #endif// #ifdef VUE3import { createSSRApp} from 'vue'// vueximport store from './store'// piniaimport pstore from './pinia-store'export function createApp() { const app = createSSRApp(App) app.use(pstore) app.use(store) return { app }}// #endif
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42