当前位置: 代码网 > it编程>编程语言>Javascript > vue3项目使用pinia状态管理器的使用

vue3项目使用pinia状态管理器的使用

2024年06月11日 Javascript 我要评论
1、首先安装piniayarn add pinia# 或使用npmnpm install pinia2、在项目的src目录下新建store文件夹,然后store目录下新建index.js / inde

1、首先安装pinia

yarn add pinia
# 或使用npm
npm install pinia

2、在项目的src目录下新建store文件夹,然后store目录下新建index.js / index.ts :

我这里是index,js

import { createpinia } from "pinia"

// 创建 pinia 实例
const pinia  = createpinia()

// 导出 pinia 实例以便将其与应用程序实例关联
export default pinia

3、 接着在项目入口文件main.js 或 main.ts 引入并使用:

import { createapp } from 'vue'
import './style.css'
import app from './app.vue'
import router from './router/router'
import store from './store/index'

createapp(app)
    .use(router)
    .use(store)
    .mount('#app')

4、然后使用definestore来定义状态存储模块,一般使用usexxxxxstore 来约定俗成的命名规范, 我这里是user.js:

import { definestore } from "pinia"

export const useuserstore = definestore({
    //id 是为了更好地区分模块
    id: 'user',
    state: () => ({
        name: 'tony',
        age: 18,
        count: 0
    }),
    getters: {
        doublecount: (state) => state.count * 2,
    },
    actions: {
        // 定义操作或异步请求
        increment() {
            // 这里访问state的数据不再是state.xxx,而是通过this
            this.count++
        }
    }
})

 5、在组件内使用store:

<template>
  <div>
    <h3>我是测试pinia状态存储的组件,我有一个子组件</h3>
    <div>userstore里的state数据:</div>
    <span>姓名: {{ name }}</span>   <span>年龄: {{ age }}</span>
    <div><button @click="handleincre">修改count:</button>count: {{ count }}</div>
    <!-- 直接调用getters的方法 -->
    <div> double count is: {{ doublecount }}</div>
  </div>
</template>

js:

<script setup>
import { ref, reactive } from 'vue'
import testchild1 from './component/testchild1.vue'
import { useuserstore } from '../../store/user';
import { storetorefs } from 'pinia'

const userstore = useuserstore()
// 通过storetorefs包裹,解构出来的属性/方法才有响应式
const { name, age, count,  doublecount} = storetorefs(userstore)
// console.log('userstore:', userstore.name, userstore.age, userstore.count)
// console.log(name.value, age.value, count.value);

// 调用store的actions的increment方法
const handleincre = () => {
    userstore.increment()
}

</script>

解构store的变量或方法时,如果没有通过storetorefs包裹,就失去了响应式:

具有响应式:

6、在store中定义异步获取用户信息方法:

6.1首先新建一个api文件夹定义模拟异步登录获取用户登录信息接口方法:

~~src/api/index

// 模拟异步登录获取用户信息
const loginuser = () => {
    return new promise((resolve, reject) => {
        settimeout(() => {
            resolve({
                name: 'tony',
                age: 18
            })
        }, 2000)
    })
}

export default {
    loginuser
}

6.2 在store,user.js中: 

引入api文件,在actions中定义getuserinfo方法,异步查询时,通常都是async和await一起搭配使用的。

import { definestore } from "pinia"
import api from '../api/index'

export const useuserstore = definestore({
    //id 是为了更好地区分模块
    id: 'user',
    state: () => ({
        name: 'tony',
        age: 18,
        count: 0,
        userinfo: {}
    }),
    getters: {
        doublecount: (state) => state.count * 2,
    },
    actions: {
        // 定义操作或异步请求
        increment() {
            // 这里访问state的数据不再是state.xxx,而是通过this
            this.count++
        },
        // 在actions中异步获取loginuser的数据
        async getuserinfo() {
            this.userinfo = await api.loginuser()
            console.log('user-info', this.userinfo);
        }
    }
})

 6.3 在vue组件中使用:

<!-- 点击---异步登录获取userinfo -->
    <button @click="getuser">异步登录获取userinfo</button>
    <div>userinfo: {{ userinfo }}</div>
// 调用store的actions的getuserinfo方法异步获取用户登录信息
const getuser = () => {
  userstore.getuserinfo()
}

 以上就是pinia的vue3使用,后面更新持续化存储。更多相关vue3 pinia状态管理器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com