pinia使用详解

pinia中只有stategetteraction,抛弃了Vuex中的Mutation

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: { // 存放数据 和data类似
  },
  mutations: { // 用来修改state和getters里面的数据
  },
  getters: { // 相当于计算属性
  },
  actions: { // vuex中用于发起异步请求
  },
  modules: {// 拆分模块
  }
})
yarn add pinia
# 或者使用 npm
npm install pinia

import { createApp } from "vue";
import App from "./App.vue";
import { createPinia } from "pinia";
const pinia = createPinia();


const app = createApp(App);
app.use(pinia);
app.mount("#app");

官网基本示例#        介绍 | Pinia 中文文档

这就是使用 pinia 在 API 方面的样子(请务必查看 Getting Started 以获取完整说明)。 您首先创建一个 Store :

// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => {
    return { count: 0 }
  },
  // 也可以定义为
  // state: () => ({ count: 0 })
  actions: {
    increment() {
      this.count++
    },
  },
})

然后你在一个组件中 使用 它:

import { useCounterStore } from '@/stores/counter'

export default {
  setup() {
    const counter = useCounterStore()

    counter.count++
    // 带自动补全 ✨
    counter.$patch({ count: counter.count + 1 })
    // 或使用 action 代替
    counter.increment()
  },
}

你甚至可以使用一个函数(类似于一个组件setup())来为更高级的用例定义一个Store:

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  function increment() {
    count.value++
  }

  return { count, increment }
})

如果你还不熟悉 setup() 和 Composition API,别担心,Pinia 也支持一组类似的 map helpers like Vuex。 您以相同的方式定义存储,但随后使用 mapStores()mapState() 或 mapActions()

const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    }
  }
})

const useUserStore = defineStore('user', {
  // ...
})

export default {
  computed: {
    // other computed properties
    // ...
    // gives access to this.counterStore and this.userStore
    ...mapStores(useCounterStore, useUserStore)
    // gives read access to this.count and this.double
    ...mapState(useCounterStore, ['count', 'double']),
  },
  methods: {
    // gives access to this.increment()
    ...mapActions(useCounterStore, ['increment']),
  },
}

一个更现实的例子#

这是一个更完整的 API 示例,您将与 Pinia 一起使用即使在 JavaScript 中也具有类型。 对于某些人来说,这可能足以在不进一步阅读的情况下开始使用,但我们仍然建议您查看文档的其余部分,甚至跳过此示例,并在阅读完所有_核心概念_后返回。

import { defineStore } from 'pinia'

export const todos = defineStore('todos', {
  state: () => ({
    /** @type {{ text: string, id: number, isFinished: boolean }[]} */
    todos: [],
    /** @type {'all' | 'finished' | 'unfinished'} */
    filter: 'all',
    // type 会自动推断为 number
    nextId: 0,
  }),
  getters: {
    finishedTodos(state) {
      // 自动完成! ✨
      return state.todos.filter((todo) => todo.isFinished)
    },
    unfinishedTodos(state) {
      return state.todos.filter((todo) => !todo.isFinished)
    },
    /**
     * @returns {{ text: string, id: number, isFinished: boolean }[]}
     */
    filteredTodos(state) {
      if (this.filter === 'finished') {
        // 自动调用其他 getter ✨
        return this.finishedTodos
      } else if (this.filter === 'unfinished') {
        return this.unfinishedTodos
      }
      return this.todos
    },
  },
  actions: {
    // 任何数量的参数,返回一个 Promise 或者不返回
    addTodo(text) {
      // 你可以直接改变状态
      this.todos.push({ text, id: this.nextId++, isFinished: false })
    },
  },
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue 3使用Pinia作为其状态管理库。Pinia是一个基于Vue 3的状态管理库,它提供了一种简单和直观的方式来管理Vue应用程序的状态。Pinia的使用方法如下: 1. 首先,你需要安装Pinia。你可以通过npm或yarn来安装Pinia库。 2. 在你的Vue应用程序的入口文件中,引入并创建一个Pinia实例。你可以使用createPinia方法创建一个全局的Pinia实例,并将其挂载到Vue应用的根实例上。 3. 创建一个store来管理状态。你可以使用Pinia提供的createStore方法来创建一个store。通过定义一个带有状态和操作的类来创建store,并将其与创建的Pinia实例相关联。 4. 在Vue组件中使用store。你可以使用provide和inject来在组件中注入和使用store。在父组件中使用provide方法来提供store实例,在子组件中使用inject方法来获取store实例。 5. 在组件中使用store的状态和操作。你可以通过在组件中使用computed属性来获取store的状态,使用methods属性来调用store的操作。 通过以上步骤,你就可以在Vue 3中使用Pinia进行状态管理了。Pinia提供了一种简单和灵活的方式来组织和管理应用程序的状态,使得状态的共享和更新变得更加容易和可靠。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [vue3+ts+vuerouter+pinia+elementplus+ts环境模板搭建及vite打包优化](https://download.csdn.net/download/qq_42717015/87775817)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Vue3中使用Pinia详解](https://blog.csdn.net/w137160164/article/details/131160122)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值