您现在的位置是:主页 > Web前端技术 > Web前端技术
Vue生态的新成员Pinia怎么用开发技术
IDCBT2022-01-13【服务器技术】人已围观
简介小编给大家分享一下Vue生态的新成员Pinia怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧
小编给大家分享一下Vue生态的新成员Pinia怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
Pinia是Vue应用程序的状态管理方案,是Vuex核心团队成员开发。感觉更像是常规的旧 javascript 导入模块,实现了很多Vuex5的提案。
Pinia同时支持Vue2和Vue3,不过下面展示的例子都是使用Vue3,Pinia的版本是Pinia@2.0.9。
Vue2和Vue3使用的Pinia版本有一点不同,因此请查看官方 Pinia 文档以获取更多信息。
安装和配置可以使用npm或者yarn安装Pinia
yarn add pinia@next # 或者 使用npm npm install pinia@next
安装完毕后,找到Vue应用程序的文件 main.js (vue-cli初始化的项目,一般都命名为main.js)。从Pinia的npm包中导入createPinia,然后使用Vue的use方法作为插件使用
//main.js import { createApp } from 'vue' import App from './App.vue' import router from './router' import { createPinia } from 'pinia' createApp(App) .use(router) .use(createPinia()) .mount('#app')
接下来,我们去创建一个 store
Store核心Pinia的Store不同于Vuex的Store。使用Vuex的时候,整个应用程序只有一个主要Store(虽然你可以拆成不同的模块,但是还是一个主存储出口)。然而,今天的主角Pinia则是开箱即用的模块化设计,不在需要一个主要的Store,可以创建不同的Store。例如,我们可以创建一个登录用户Store。
// store/loggedInUser.js import { defineStore } from 'pinia' export const useLoggedInUserStore = defineStore({ // id 是必填的,并且所有 Store 中唯一。因为Pinia会将它在devtools显示 id: 'loggedInUser', state () { return { name: '太凉', age: 18, email: 'fake@email.com' } }, getters: {}, actions: {} })
上面我们创建了一个登录用户Store,接下来我们可以直接在组件中引用,然后在setup函数中调用useLoggedInUserStore
<template> <div>PiniaApage</div> <div>姓名:{{user.name}}</div> <div>年龄:{{user.age}}</div> </template> <script> import { useLoggedInUserStore } from '@/store/loggedInUser.js' export default { name: 'PiniaDemoPage1', setup () { const user = useLoggedInUserStore() return { user } } } </script>标签:很赞哦! ()