pinia的基本使用

文章介绍了如何在Vue2和Vue3项目中安装和使用Pinia进行状态管理。通过`yarnaddpinia`或`npminstallpinia`安装,然后在Vue应用中引入并创建Pinia实例。定义store使用`defineStore`,并展示了在组件中如何通过`useStore`访问和使用store。此外,还提到了`storeToRefs`用于从store中提取响应式属性。
摘要由CSDN通过智能技术生成

1.安装pinia

yarn add pinia 或者使用 npm install pinia

2.使用

2.1如果您使用的是 Vue 2,您还需要安装一个插件并将创建的 pinia 注入应用程序的根目录:

import { createPinia, PiniaVuePlugin } from 'pinia'
Vue.use(PiniaVuePlugin)
const pinia = createPinia()

new Vue({
  el: '#app',
  // 其他选项...
  // ...
  // 注意同一个 `pinia` 实例可以在多个 Vue 应用程序中使用
  // 同一个页面
  pinia,
})

2.2 Vue3中 使用pinia

import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia).mount('#app')

3.定义一个store

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

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

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

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


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

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']),
  },
}

4.使用 store

我们正在 定义 一个 store,因为在 setup() 中调用 useStore() 之前不会创建 store:

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

export default {
  setup() {
    const store = useStore()

    return {
      // 您可以返回整个 store 实例以在模板中使用它
      store,
    }
  },
}

请注意,store 是一个用reactive 包裹的对象,这意味着不需要在getter 之后写.value,但是,就像setup 中的props 一样,我们不能对其进行解构:

export default defineComponent({
  setup() {
    const store = useStore()
    // ❌ 这不起作用,因为它会破坏响应式
    // 这和从 props 解构是一样的
    const { name, doubleCount } = store

    name // "eduardo"
    doubleCount // 2

    return {
      // 一直会是 "eduardo"
      name,
      // 一直会是 2
      doubleCount,
      // 这将是响应式的
      doubleValue: computed(() => store.doubleCount),
      }
  },
}
)

为了从 Store 中提取属性同时保持其响应式,您需要使用storeToRefs()。 它将为任何响应式属性创建 refs。 当您仅使用 store 中的状态但不调用任何操作时,这很有用:

import { storeToRefs } from 'pinia'

export default defineComponent({
  setup() {
    const store = useStore()
    // `name``doubleCount` 是响应式引用
    // 这也会为插件添加的属性创建引用
    // 但跳过任何 action 或 非响应式(不是 ref/reactive)的属性
    const { name, doubleCount } = storeToRefs(store)

    return {
      name,
      doubleCount
    }
  },
})
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Pinia是Vue的官方状态管理库,用于在Vue3项目中实现数据共享。下面是使用Pinia的基本步骤: 1. 安装Pinia:在Vue3项目中,使用npm或yarn安装Pinia库。 2. 创建Pinia实例:在项目的入口文件中,创建一个Pinia实例并将其导出。 3. 定义状态:在需要共享状态的组件中,使用`defineStore`函数定义一个状态存储对象。 4. 注册状态:在组件中使用`useStore`函数注册状态,并在模板中使用。 5. 使用状态:在组件中可以通过`$store`访问状态,并在模板中使用。 下面是一个使用Pinia的示例代码: ```javascript // main.js import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' const app = createApp(App) const pinia = createPinia() app.use(pinia) app.mount('#app') // store.js import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++ }, decrement() { this.count-- } } }) // Counter.vue <template> <div> <p>Count: {{ $store.counter.count }}</p> <button @click="$store.counter.increment()">Increment</button> <button @click="$store.counter.decrement()">Decrement</button> </div> </template> <script> import { useCounterStore } from './store' export default { setup() { const counterStore = useCounterStore() return { counterStore } } } </script> ``` 在上面的示例中,我们首先在`main.js`中创建了一个Pinia实例,并将其应用于Vue应用。然后,在`store.js`中定义了一个名为`counter`的状态存储对象,其中包含一个名为`count`的状态和两个操作。最后,在`Counter.vue`组件中使用`useCounterStore`函数注册状态,并在模板中使用`$store.counter.count`访问状态。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值