Pinia的十个简答小案例

      Pinia的十个简答小案例_第1张图片

1. 使用Pinia进行状态管理:

import { defineStore } from 'pinia'

export const useCounterStore = defineStore({
  id: 'counter',
  state: () => ({
    count: 0
  }),
  actions: {
    increment() {
      this.count++
    },
    decrement() {
      this.count--
    }
  }
})

2. 在组件中使用Pinia:



3. 使用getters获取状态:

import { defineStore } from 'pinia'

export const useCounterStore = defineStore({
  id: 'counter',
  state: () => ({
    count: 0
  }),
  getters: {
    isPositive() {
      return this.count > 0
    }
  },
  actions: {
    increment() {
      this.count++
    },
    decrement() {
      this.count--
    }
  }
})

4. 在另一个store中依赖另一个store:

import { defineStore } from 'pinia'
import { useCounterStore } from './counter'

export const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    name: 'test',
    age: 20
  }),
  getters: {
    message() {
      return `${useCounterStore().count} ${this.name} ${this.age}`
    }
  }
})

5. 在插件中注册store:

import { createPinia } from 'pinia'
import { useCounterStore } from './store'

const app = createApp(App)

app.use(createPinia())

app.provide('counterStore', useCounterStore())

app.mount('#app')

6. 在组件外部使用store:

import { useCounterStore } from './store'

useCounterStore().increment()

7. 在store中使用localStorage:

import { defineStore } from 'pinia'

export const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    name: localStorage.getItem('name') || '',
    age: localStorage.getItem('age') || ''
  }),
  actions: {
    setName(name) {
      this.name = name
      localStorage.setItem('name', name)
    },
    setAge(age) {
      this.age = age
      localStorage.setItem('age', age)
    }
  }
})

8. 使用action的回调函数:

import { defineStore } from 'pinia'

export const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    name: '',
    age: ''
  }),
  actions: {
    async fetchData() {
      const data = await fetch('https://api.example.com/user')
      const { name, age } = await data.json()
      this.name = name
      this.age = age
    }
  }
})

9. 使用mutation:

import { defineStore } from 'pinia'

export const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    name: '',
    age: ''
  }),
  mutations: {
    setName(name) {
      this.name = name
    },
    setAge(age) {
      this.age = age
    }
  },
  actions: {
    fetchData() {
      fetch('https://api.example.com/user')
        .then((data) => data.json())
        .then(({ name, age }) => {
          this.setName(name)
          this.setAge(age)
        })
    }
  }
})

10. 使用插件扩展Pinia:

import { createPinia } from 'pinia'
import { useCounterStore } from './store'

function myPlugin(pinia) {
  pinia.use((context) => {
    context.$counter = useCounterStore()
  })
}

const app = createApp(App)

app.use(createPinia())
app.use(myPlugin)

app.mount('#app')

你可能感兴趣的:(Pinia,vue,java,开发语言)