Pinia的基础使用

630 阅读1分钟

1.使用Pinia第一步

使用熟悉的方式载入pinia:npm install pinia

或者使用vite手动选择pinia

2.配置main.js

在创建好的vue项目中的main.js中进行如下配置:

import { createApp } from 'vue'
import {createPinia} from 'pinia'  // 导入创建pinia
import App from './App.vue'
import router from './router'

createApp(App).use(createPinia()).use(router).mount('#app') // 加载

3.创建conter.js

(1)在src文件夹下新建stores文件和counter.js:

pinia1.png

(2)counter.js中有相应配置:

import {ref,computed,reactive} from 'vue' 
import {defineStore} from 'pinia'

export const useCounterStore = defineStore('counter',()=>{
    // 定义数据(state)使用ref或者reactive
    const count = ref(1)
    const myData = reactive({
        name:'kjs',
        age:11
    })
    // getter定义(计算属性)
    const doubleCount = computed(()=>{ 
         return count.value*2
    })
    // 定义修改数据的方式(action 同步+异步)
    function increment(){ 
        count.value++
    }
    // 以对象的方式return供组件使用
    return {count,myData,doubleCount,increment}
})

pinia中ref相当于state,computed相当于getter,function相当于action

(3)在组件中的使用

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

通常重新给一个名字:const storeCount = useCounterStore()

在模块中可以直接通过storeCount.的方式访问到return出来的所有方法和属性

!这里在使用ref的数据时不需要加value即可直接访问

最后Vuex和Pinia的区别

vuex有五个属性state,getters,mutations,actions,modules

pinia只有三个属性state,getters,actions 1.vuex中的mutations做同步操作,actions做异步操作,而pinia中的actions可以做同步+异步