pinia---状态管理工具

state、actions、getters

对ts支持好

vuex和pinia区别

  1. Vuex`的核心概念有:`state`,`getters`,`mutations`,`actions`,`moudles`五个部分

  2. `Pinia`的核心概念有:`state`,`getter`,`action`三个部分

  3. `Vuex`对state的修改推荐使用`mutations`中的方法进行修改,

  4. `Pinia`直接对state进行修改

  5. Pinia中 getter,action 也可通过 `this` 访问整个 store 实例

安装:npm install pinia

main.js

javascript 复制代码
// 导入createApp函数
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

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

//  创建App实例挂载到id为app的dom元素
const app = createApp(App)
app.use(pinia)

app.mount('#app')

store/user.js

javascript 复制代码
// 定义用户仓库
import { defineStore } from 'pinia'
// defineStore() 创建store实例的函数 
// 第一个参数 store的唯一标识 类似于模块
// 第二个参数 对象描述仓库可以提供state getters actions
// 返回值 是创建store实例的方法
// 规范 useXXXXStore
const useUserStore = defineStore('user',{
  // state getters actions
  state: ()=> {
    return  {
      userInfo: {
        username: 'admin',
        age: 20
      }
    }
  },
  //转成大写
  getters:{
    upperCase(){
      return this.userInfo.username.toUpperCase()
    }
  },
  //同步异步都可以
  actions:{
    change(){
      this.userInfo.username="香香"
    }
  }
})
//导出
// 导出user仓库实例的方法
export default useUserStore

App.vue

javascript 复制代码
<template>
  <div>
    <button @click="change">按钮</button>
    <p>{{ userStore.userInfo.username }}</p>
    <button @click="userStore.change">第二种方式</button>
    <!-- 变成大写 -->
    <p>{{ userStore.upperCase }}</p>
  </div>
</template>

<script setup>
import useUserStore  from './store/user'
const userStore =useUserStore ()
console.log(userStore)
const change=()=>{
  userStore.change()
}
</script>

<style>

</style>

pinia模块化

如果有多个模块ia,就需要导入很多,代码会很臃肿,所以在一个模块实现,app.vue只需要导入一次就能拿到值'

store/index.js'

javascript 复制代码
import useUserStore from "./user";
import useCounterStore from "./counter";

export default function useStore() {
  return {
    user:  useUserStore(),
    counter: useCounterStore()
  }
}
  

在App.vue

javascript 复制代码
<template>
    <p>{{store.counter.num}}</p>
</template>
//导入
import useStore from './store/index.js'
//调用赋值
const store=useStore()
相关推荐
小白学大数据5 分钟前
如何避免爬虫因Cookie过期导致登录失效
开发语言·爬虫·python·scrapy
烛阴43 分钟前
Promise无法中断?教你三招优雅实现异步任务取消
前端·javascript
爱吃烤鸡翅的酸菜鱼1 小时前
【SpringMVC】概念引入与连接
java·开发语言·mysql
小白学大数据1 小时前
Python自动化解决滑块验证码的最佳实践
开发语言·python·自动化
碎梦归途1 小时前
23种设计模式-行为型模式之策略模式(Java版本)
java·开发语言·jvm·设计模式·策略模式·行为型模式
Albert Edison1 小时前
Python入门基础
开发语言·python
小余吃大鱼1 小时前
OpenStack私有云详细介绍
开发语言·php·openstack
画个大饼1 小时前
Swift:什么是Optional?其背后的机制是什么?什么是Unconditional Unwrapping?
开发语言·ios·swift
T0uken1 小时前
【Python】Matplotlib:立体永生花绘制
开发语言·python·matplotlib
sniper_fandc1 小时前
JVM(Java虚拟机)详解
java·开发语言·jvm