vue3中使用pinia进行数据状态管理

我们在学习vue3视频中,数据通信和管理推荐使用pinia,所以今天我们就来在自己的项目中进行实际使用。

pinia我们需要进行安装

npm install pinia

安装完成以后,在main.js中use一下

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

然后使用这个状态管理库需要进行一些规范,通常的做法是在src目录目录下创建一个stores目录,本地项目是做来一个导航数据的存取,因为这个导航数据很多地方都要用到。

src/stores/categoryStore.js,内容如下:

import { defineStore } from "pinia";
import axios from "axios";

export const useCategoryStore = defineStore('category', {
    state: () => ({
        cateList: [],
        cateArray: {},
        cateExists: false
    }),
    actions: {
        async fetchCatelist(){
            if(!this.cateExists){
                const res = await axios.get("http://localhost:5000/api/cate_list");
                this.cateList = res.data.data;
                for (let i=0; i< this.cateList.length;i++){
                    this.cateArray[this.cateList[i].id] = this.cateList[i].cate_name;
                }
                this.cateExists = true;
            }
        }
    }
});

我们除了获取cateList数据列表,还有一个用于获取当前菜单名字的cateArray,还有一个cateExists对象,用于确认当前数据是否存在,存在就不再次从接口获取。

由于我们的菜单数据在打开网站的时候就需要获取,所以我们需要使用onMounted这个钩子,在前端挂载Dom对象的时候就加载数据,所以我们需要在入口的app.vue文件中进行处理。

import { onMounted } from 'vue';
import { useCategoryStore } from '@/stores/categoryStore';
const useCategory = useCategoryStore();

onMounted(()=>{
    useCategory.fetchCatelist();
});

然后我们就可以在菜单组件中进行使用了。

import { ref } from 'vue';
import { useCategoryStore } from '@/stores/categoryStore';
import { storeToRefs } from 'pinia';
const useCategory = useCategoryStore();
const { cateList } = storeToRefs(useCategory);

模板中调用方法如下:

<ul class="layui-nav layui-nav-light">
<li class="layui-nav-item">
    <router-link :to="{name: 'home'}">首页</router-link>
</li>
<li class="layui-nav-item" v-for="cate in cateList" :key="cate.id">
    <router-link :to="{name: 'cate', params: {id: cate.id}}">{{ cate.cate_name }}</router-link>
</li>
</ul>

pinia中还有一个getters属性,这个类似于计算属性,我们目前还有使用,后面使用的话在补充在这里。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/1047

评论列表