当前位置:首页 > 编程笔记 > 正文
已解决

Pinia的十个简答小案例

来自网友在路上 143843提问 提问时间:2023-11-03 00:08:17阅读次数: 43

最佳答案 问答题库438位专家为你答疑解惑

      

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

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

2. 在组件中使用Pinia:

<template><div><p>{{ counter.count }}</p><button @click="counter.increment()">Increment</button><button @click="counter.decrement()">Decrement</button></div>
</template><script>
import { useCounterStore } from './store'export default {setup() {const counter = useCounterStore()return {counter}}
}
</script>

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 = namelocalStorage.setItem('name', name)},setAge(age) {this.age = agelocalStorage.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 = namethis.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')

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"Pinia的十个简答小案例":http://eshow365.cn/6-30624-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!