【Pinia】Pinia的安装和配置
工程化项目中的安装
如果是通过脚手架搭建的项目可以通过NPM
或者Yarn
安装到项目当中:
1 | npm install pinia |
CDN 方式引入与使用
如果没有使用脚手架的项目也可以通过CDN来引入
Pinia
的js文件来使用。
项目结构: ::: file-tree - pinia1 - js - lib - pinia.min.js # pinia 文件 - vueDemi.js # 一款开发工具。允许你为 Vue 2 和 3 编写通用 Vue 库。而无需担心用户安装的版本。 - vue.min.js # Vue3 文件 :::
接着在pinial1
下创建一个index.html
文件。
使用!
生成模板后引入js文件: 1
2
3<script src="./lib/vue.min.js"></script>
<script src="./lib/vueDemi.js"></script>
<script src="./lib/pinia.min.js"></script>
使用createPinia()
来将其注入到Vue实例中:
1
2
3
4
5
6
7
8
9
10
11
12...
<div id="app"></div>
...
<script type="module">
// 创建 Vue 实例
const app = Vue.createApp({
setup() {},
});
// 注入 Pinia 对象
app.use(createPinia());
app.mount("#app");
</script>
接下来创建一个store
文件: ::: code-tabs @tab js/store.js 1
2
3
4
5
6
7
8
9const { defineStore } = Pinia; // 引入 defineStore 函数
// 创建 id=counter 的 store
const useCounterStore = defineStore("counter", {
state: () => ({
count: 10, // 声明一个 state count 并初始化为 10
}),
getters: {},
actions: {},
});
在上述代码中创建了一个state
,
count
被赋值为10。
之后,在index.html
中引入store.js
文件:
1
2
3
4
5<script src="./lib/vue.min.js"></script>
<script src="./lib/vueDemi.js"></script>
<script src="./lib/pinia.min.js"></script>
<!-- 引入 store 文件 -->
<script src="./js/store.js"></script>
在index.html
中调用store.js
文件的useCounterStore
方法获取store
对象couter
,并把该对象在Vue的setup()
中返回:
1
2
3
4
5
6
7
8
9
10
11
12
13
14<script type="module">
const { createApp } = Vue
const { createPinia } = Pinia
const app = Vue.createApp({ // 创建 Vue 实例对象 app
setup() {
const store = useCounterStore(); // 调用 useCounterStore 方法获取 store 对象 counter
return {
store // 返回 store 对象,方便 DOM 中使用
}
}
});
app.use(createPinia()) // 将 pinia 插件用于 Vue 实例对象 app 中
app.mount('#app');
</script>
在DOM结构中: 1
2
3<div id="app">
<h1>{{ store.count }}</h1>
</div>
预览并查看页面即可。
:::: demo-wrapper no-padding ::: center ::: ::::