pinia的使用

前言:

当我们构建一个中大型单页应用,需要考虑如何更好地在组件外部管理状态的时候,我们就会借助一些状态管理器帮助我们完成这些操作。

相比于 VuexPinia 提供了更简洁直接的组合式风格的API(去掉了 mutation ),action可以支持同步和异步。去掉了 modules 的概念,每一个 store 都是一个独立的模块。

其次,在使用 TypeScript 时也提供了比较完善的类型推导。所以在开发vue3的项目的时候,我们更为推荐使用pinia。

安装pinia

pnpm install pinia
# or with yarn
yarn add pinia
# or with npm
npm install pinia

创建pinia 实例

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

app.use(pinia)
app.mount('#app')

定义store示例

import { defineStore } from 'pinia'

//您可以将'defineStore()'的返回值命名为任意名称,

//但最好使用store的名称,并用“use”将其包围,这是一个不错的规范

//(例如`useUserStore`、`useCartStore`和`useProductStore`)

//第一个参数是应用程序中存储的唯一id
export const useAdminStore = defineStore('admin', {
  // 其他选项...
})

//定义一个完整的store
//与 Vue的选项API类似,我们也可以传递带有属性的选项对象。state actions getters
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0, name: 'Eduardo' }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})
//您可以将其视为store的属性,也可以将其视为vue的属性,
//state => data
//getters => computed
//actions => methods
//这样会更容易记忆

/* 还有另一种可能的语法来定义存储。与 Vue3组合API的设置函数类似,
我们可以传入一个函数来定义反应式属性和方法,并返回一个包含我们要公
开的属性和方法的对象。*/
export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const name = ref('Eduardo')
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  return { count, name, doubleCount, increment }
})

使用pinia


剖析pinia各个选项

state

//给 state 加上类型推导
interface UserInfo {
  name: string
  age: number
}

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      userList: [] as UserInfo[],
      user: null as UserInfo | null,
    }
  },
})


//或者给整个state加上类型推导
interface UserInfo {
  name: string
  age: number
}

interface State {
  userList: UserInfo[]
  user: UserInfo | null
}

export const useUserStore = defineStore('user', {
  state: (): State => {
    return {
      userList: [],
      user: null,
    }
  },
})
访问state
import { useAdminStore } from '@/stores/user'
    
const store = useAdminStore()
console.log('name',store.name)
重置state
import { useAdminStore } from '@/stores/user'
    
const store = useAdminStore()
store..$reset()
更改state
//1.直接改变
store.name = 'new name'
//2.$patch
store.$patch({
  sex: 1,
  age: store.age + 1,
  name: 'new name',
})
//或
useUserStore.$patch((state) => {
  state.items.push({ name: 'jack', age: 18 })
  state.ishasStatus = true
})

getters

定义getters
export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
})
//添加类型约束
export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  getters: {
    // automatically infers the return type as a number
    doubleCount(state) {
      return state.count * 2
    },
    // the return type **must** be explicitly set
    doublePlusOne(): number {
      // autocompletion and typings for the whole store ✨
      return this.doubleCount + 1
    },
  },
})
访问getters



访问其他getters
export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
    doubleCountPlusOne() {
      // autocompletion
      return this.doubleCount + 1
    },
  },
})
getters参数传递
//@/stores/admin
export const useAdminStore = defineStore('admin', {
  getters: {
    getUserById: (state) => {
      return (userId) => state.users.find((user) => user.id === userId)
    },
  },
})

//组件中使用


actions

定义actions
export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  actions: {
    // 因为我们依赖“this”,所以不能使用箭头函数
    increment() {
      this.count++
    },
    randomizeCounter() {
      this.count = Math.round(100 * Math.random())
    },
  },
})
/*与 getter 一样,操作通过完全键入(和自动完成)支持来访问整个商店实例。
与 getter 不同,操作可以是异步的*/
import { mande } from 'mande'

const api = mande('/api/users')

export const useUsers = defineStore('users', {
  state: () => ({
    userData: null,
    // ...
  }),

  actions: {
    async registerUser(login, password) {
      try {
        this.userData = await api.post({ login, password })
        console.log(`Welcome back ${this.userData.name}!`)
      } catch (error) {
        console.log(error)
        // let the form component display the error
        return error
      }
    },
  },
})
使用actions

你可能感兴趣的:(vue3.0,vue.js,前端,javascript,状态管理器,pinia,vue3,vuex)