vue3+uniapp 创建pinia

2024-02-25  本文已影响0人  我是七月

1新建uniapp项目

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

2安装pinia

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

npm init -y
npm install pinia --save

3新建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 = '已退出登录'
      }
    }
})

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>


参考:
https://blog.csdn.net/qq_20111965/article/details/123888080
https://blog.csdn.net/u010017719/article/details/129177431
https://blog.csdn.net/qq_57399113/article/details/135383646

上一篇 下一篇

猜你喜欢

热点阅读