Pinia的安装和配置

Sy_ Lv6

工程化项目中的安装

如果是通过脚手架搭建的项目可以通过NPM或者Yarn安装到项目当中:

::: npm-to

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
9
const { 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
20250226193628
:::
::::

  • 标题: Pinia的安装和配置
  • 作者: Sy_
  • 创建于 : 2025-06-15 00:51:35
  • 更新于 : 2025-06-15 00:51:35
  • 链接: https://shenying.online//demo/rrm6slri/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论