首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【Vue】Pinia介绍 && 详细使用

【Vue】Pinia介绍 && 详细使用

原创
作者头像
lirendada
发布2026-02-06 13:01:47
发布2026-02-06 13:01:47
770
举报
文章被收录于专栏:前端前端

Ⅰ. Pinia的介绍

Pinia 是一个状态管理工具,Vue的专属状态管理库,它允许你跨组件或页面共享状态,让多个组件共享数据

那 Pinia 中存什么?

  • 多个组件共享的数据,才存储在 Pinia 中
  • 某个组件中的私有数据,依旧存储在组件自身内部

例如:

  • 登陆的用户名需要在首页、个人中心页、搜索页、商品详情页使用,则用户名存储在 Pinia 中
  • 新闻详情数据,只有在新闻详情页查看,则存储在组件自身内部

Ⅱ. Pinia的使用

一、例子准备

1. 目标

创建项目,为学习 Pinia 做准备

  • 需求1:App.vue 作为根组件
  • 需求2:子组件 Add 和子组件 Sub,作为在 App.vue 的子组件
  • 需求3:三个组件共享库存数据(保持同步)

2. 效果

3. 代码示例

components/Add.vue文件:

代码语言:javascript
复制
<script setup></script>

<template>
  <div>
    <h3>Add组件</h3>
    <p>已知库存数: 0</p>
    <button>库存+1</button>
  </div>
</template>

components/Sub.vue文件:

代码语言:javascript
复制
<script setup></script>

<template>
  <div>
    <h3>Sub组件</h3>
    <p>已知库存数: 0</p>
    <button>库存-1</button>
  </div>
</template>

App.vue文件:

代码语言:javascript
复制
<script setup>
    import Add from '@/components/Add.vue'
    import Sub from '@/components/Sub.vue'
</script>

<template>
  <div>
    <h1>根组件</h1>
    <p>
      <span>库存总数: </span>
      <input type="number" />
    </p>
  </div>
  <hr />
  <Add />
  <hr />
  <Sub />
</template>

<style>
#app {
  width: 350px;
  margin: 60px auto;
  border: 1px solid #ccc;
  padding: 4px;
}
</style>

二、Pinia -- 准备store并渲染数据

1. 下载pinia

代码语言:javascript
复制
npm i pinia

2. 创建pinia实例并注册

main.js文件:

代码语言:javascript
复制
// 导入
import { createPinia } from 'pinia'

// 创建 pinia 实例
const pinia = createPinia()

// 注册实例
app.use(pinia)

3. 定义仓库

创建 src/store/stock.js 文件,用来管理共享的库存数据。

defineStore 是 Pinia 定义仓库的核心方法。语法如下所示:

代码语言:javascript
复制
import { defineStore } from 'pinia'

export const useXxxStore = defineStore(
  id: string,
  optionsOrSetup: Options | Setup
)
  1. id (string)
    1. 仓库唯一标识符,通常是英文命名。
    2. 必填。Pinia 内部会用它来区分不同的 store。
    3. 示例:'user''cart'
  2. optionsOrSetup (Options | Setup) 有两种写法:
    1. Options 对象式写法(类似 Vuex):
    代码语言:javascript
    复制
    {
      state: () => ({ ... }),   // 定义响应式数据
      getters: { ... },         // 计算属性
      actions: { ... }          // 方法,可异步
    }
    1. Setup 函数式写法(类似组合式 API):
    代码语言:javascript
    复制
    () => {
      const count = ref(0)
      const double = computed(() => count.value * 2)
      function increment() { count.value++ }
      return { count, double, increment }
    }
  3. useXxxStore:返回值,是一个函数。
    1. 在组件或逻辑中调用 useXxxStore() 就能拿到 store 实例。
    2. Store 实例包含你定义的 state、getter、action,并且是响应式的。
    3. 命名规则:最好含有 store 的名字,且以 use 开头,以 Store 结尾。比如 useUserStoreuseCartStoreuseProductStore
① 组合式API(Setup函数)
代码语言:javascript
复制
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 定义一个名为 stock的store 并导出
export const useStockStore = defineStore('stock', () => {
  // 初始化库存数据
  const stock = ref(20)
  
  // 计算库存的两倍
  const doubleStock = computed(() => {
    return stock.value * 2
  })
  
  // 增加
  const addStock = () => {
    stock.value++
  }
  
  // 减少
  const subStock = () => {
    stock.value--
  }
  
  // 返回共享数据和操作函数
  return {
    stock,
    doubleStock,
    addStock,
    subStock
  }
})
② 选项式API(Option对象)
代码语言:javascript
复制
import { defineStore } from 'pinia'

// 定义一个名为 stock的store 并导出
export const useStockStore = defineStore('stock', {
  // 共享数据
  state: () => ({
    // 库存初始值
    stock: 20
  }),
  
  // 基于共享数据的计算属性
  getters: {
    // 计算库存的两倍
    doubleStock: (state) => state.stock * 2
  },
  
  // 修改共享数据的方法
  actions: {
    // 增加库存
    addStock() {
      this.stock++
    },
    // 减少库存
    subStock() {
      this.stock--
    }
  }
})

4. 使用仓库

Add.vue文件:

代码语言:javascript
复制
<script setup>
    // 导入 使用库存仓库
    import { useStockStore } from '@/store/stock.js'
    
    // 创建库存仓库
    const stockStore = useStockStore()
</script>

<template>
  <div>
    <h3>Add组件</h3>
    <p>已知库存数: {{ stockStore.stock }}</p>
    <button @click="stockStore.addStock()">库存+1</button>
  </div>
</template>

Sub.vue文件:

代码语言:javascript
复制
<script setup>
    // 导入 使用库存仓库
    import { useStockStore } from '@/store/stock.js'
    
    // 创建库存仓库
    const stockStore = useStockStore()
</script>

<template>
  <div>
    <h3>Sub组件</h3>
    <p>已知库存数: {{ stockStore.stock }}</p>
    <button @click="stockStore.subStock()">库存-1</button>
  </div>
</template>

App.vue文件:

代码语言:javascript
复制
<script setup>
    import Add from './components/Add.vue'
    import Sub from './components/Sub.vue'
    import { useStockStore } from '@/store/stock'
    const stockStore = useStockStore()
</script>

<template>
  <h1>根组件</h1>
  库存总数:
  <input
    type="number"
    v-model.number="stockStore.stock" />
  <p>stock 的翻倍值 = {{ stockStore.doubleStock }}</p>
  <hr />
  <Add />
  <hr />
  <Sub />
</template>

<style>
#app {
  width: 350px;
  margin: 100px auto;
  padding: 5px 10px;
  border: 1px solid #ccc;
}
</style>

Ⅲ. Pinia重构待办任务案例

components/TodoHeader.vue

代码语言:javascript
复制
<script setup></script>

<template>
  <header class="header">
    <h1>todos</h1>
    <input class="new-todo" placeholder="What needs to be finished?" autofocus />
  </header>
</template>

components/TodoMain.vue

代码语言:javascript
复制
<script setup></script>

<template>
  <section class="main">
    <input id="toggle-all" class="toggle-all" type="checkbox" />
    <label for="toggle-all">Mark all as complete</label>
    <ul class="todo-list">
      <li>
        <div class="view">
          <input class="toggle" type="checkbox" />
          <label>Buy eggs</label>
          <button class="destroy"></button>
        </div>
      </li>
      <li>
        <div class="view">
          <input class="toggle" type="checkbox" checked />
          <label>打王者</label>
          <button class="destroy"></button>
        </div>
      </li>
    </ul>
  </section>
</template>

components/TodoFooter.vue

代码语言:javascript
复制
<script setup></script>

<template>
  <footer class="footer">
    <span class="todo-count"><strong>0</strong> item left</span>
    <ul class="filters">
      <li>
        <a href="#/" class="selected">All</a>
      </li>
      <li>
        <a href="#/active">Active</a>
      </li>
      <li>
        <a href="#/completed">Completed</a>
      </li>
    </ul>
    <button class="clear-completed">
      Clear completed
    </button>
  </footer>
</template>

App.vue

代码语言:javascript
复制
<script setup>
    import './assets/style.css'
    import TodoHeader from './components/TodoHeader.vue'
    import TodoMain from './components/TodoMain.vue'
    import TodoFooter from './components/TodoFooter.vue'
</script>

<template>
  <section class="todoapp">
    <todo-header />
    <todo-main />
    <todo-footer />
  </section>
</template>

assets/style.css

代码语言:javascript
复制
@charset 'utf-8';

html,
body {
  margin: 0;
  padding: 0;
}

button {
  margin: 0;
  padding: 0;
  border: 0;
  background: none;
  font-size: 100%;
  vertical-align: baseline;
  font-family: inherit;
  font-weight: inherit;
  color: inherit;
  -webkit-appearance: none;
  appearance: none;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

body {
  font:
    14px 'Helvetica Neue',
    Helvetica,
    Arial,
    sans-serif;
  line-height: 1.4em;
  background: #f5f5f5;
  color: #111111;
  min-width: 230px;
  max-width: 550px;
  margin: 0 auto;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  font-weight: 300;
}

.hidden {
  display: none;
}

.todoapp {
  background: #fff;
  margin: 130px 0 40px 0;
  position: relative;
  box-shadow:
    0 2px 4px 0 rgba(0, 0, 0, 0.2),
    0 25px 50px 0 rgba(0, 0, 0, 0.1);
}

.todoapp input::-webkit-input-placeholder {
  font-style: italic;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.4);
}

.todoapp input::-moz-placeholder {
  font-style: italic;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.4);
}

.todoapp input::input-placeholder {
  font-style: italic;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.4);
}

.todoapp h1 {
  position: absolute;
  top: -100px;
  width: 100%;
  font-size: 50px;
  font-weight: 200;
  text-align: center;
  color: #b83f45;
  -webkit-text-rendering: optimizeLegibility;
  -moz-text-rendering: optimizeLegibility;
  text-rendering: optimizeLegibility;
}

.new-todo,
.edit {
  position: relative;
  margin: 0;
  width: 100%;
  font-size: 24px;
  font-family: inherit;
  font-weight: inherit;
  line-height: 1.4em;
  color: inherit;
  padding: 6px;
  border: 1px solid #999;
  box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
  box-sizing: border-box;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.new-todo {
  padding: 16px 16px 16px 60px;
  height: 65px;
  border: none;
  background: rgba(0, 0, 0, 0.003);
  box-shadow: inset 0 -2px 1px rgba(0, 0, 0, 0.03);
}

.main {
  position: relative;
  z-index: 2;
  border-top: 1px solid #e6e6e6;
}

.toggle-all {
  width: 1px;
  height: 1px;
  border: none; /* Mobile Safari */
  opacity: 0;
  position: absolute;
  right: 100%;
  bottom: 100%;
}

.toggle-all + label {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 45px;
  height: 65px;
  font-size: 0;
  position: absolute;
  top: -65px;
  left: -0;
}

.toggle-all + label:before {
  content: '';
  display: inline-block;
  font-size: 22px;
  color: #949494;
  padding: 10px 27px 10px 27px;
  -webkit-transform: rotate(90deg);
  transform: rotate(90deg);
}

.toggle-all:checked + label:before {
  color: #484848;
}

.todo-list {
  margin: 0;
  padding: 0;
  list-style: none;
}

.todo-list li {
  position: relative;
  font-size: 24px;
  border-bottom: 1px solid #ededed;
}

.todo-list li:last-child {
  border-bottom: none;
}

.todo-list li.editing {
  border-bottom: none;
  padding: 0;
}

.todo-list li.editing .edit {
  display: block;
  width: calc(100% - 43px);
  padding: 12px 16px;
  margin: 0 0 0 43px;
}

.todo-list li.editing .view {
  display: none;
}

.todo-list li .toggle {
  text-align: center;
  width: 40px;
  /* auto, since non-WebKit browsers doesn't support input styling */
  height: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  margin: auto 0;
  border: none; /* Mobile Safari */
  -webkit-appearance: none;
  appearance: none;
}

.todo-list li .toggle {
  opacity: 0;
}

.todo-list li .toggle + label {
  /*
  Firefox requires `#` to be escaped -
  https://bugzilla.mozilla.org/show_bug.cgi?id=922433
  IE and Edge requires *everything* to be escaped to render, so we do that
  instead of just the `#` - https://developer.microsoft.com/en-us/microsoft-
  edge/platform/issues/7157459/
  */
  background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23949494%22%20stroke-width%3D%223%22/%3E%3C/svg%3E');
  background-repeat: no-repeat;
  background-position: center left;
}

.todo-list li .toggle:checked + label {
  background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%2359A193%22%20stroke-width%3D%223%22%2F%3E%3Cpath%20fill%3D%22%233EA390%22%20d%3D%22M72%2025L42%2071%2027%2056l-4%204%2020%2020%2034-52z%22%2F%3E%3C%2Fsvg%3E');
}

.todo-list li label {
  overflow-wrap: break-word;
  padding: 15px 15px 15px 60px;
  display: block;
  line-height: 1.2;
  transition: color 0.4s;
  font-weight: 400;
  color: #484848;
}

.todo-list li.completed label {
  color: #949494;
  text-decoration: line-through;
}

.todo-list li .destroy {
  display: none;
  position: absolute;
  top: 0;
  right: 10px;
  bottom: 0;
  width: 40px;
  height: 40px;
  margin: auto 0;
  font-size: 30px;
  color: #949494;
  transition: color 0.2s ease-out;
}

.todo-list li .destroy:hover,
.todo-list li .destroy:focus {
  color: #c18585;
}

.todo-list li .destroy:after {
  content: '×';
  display: block;
  height: 100%;
  line-height: 1.1;
}

.todo-list li:hover .destroy {
  display: block;
}

.todo-list li .edit {
  display: none;
}

.todo-list li.editing:last-child {
  margin-bottom: -1px;
}

.footer {
  padding: 10px 15px;
  height: 20px;
  text-align: center;
  font-size: 15px;
  border-top: 1px solid #e6e6e6;
}

.footer:before {
  content: '';
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  height: 50px;
  overflow: hidden;
  box-shadow:
    0 1px 1px rgba(0, 0, 0, 0.2),
    0 8px 0 -3px #f6f6f6,
    0 9px 1px -3px rgba(0, 0, 0, 0.2),
    0 16px 0 -6px #f6f6f6,
    0 17px 2px -6px rgba(0, 0, 0, 0.2);
}

.todo-count {
  float: left;
  text-align: left;
}

.todo-count strong {
  font-weight: 300;
}

.filters {
  margin: 0;
  padding: 0;
  list-style: none;
  position: absolute;
  right: 0;
  left: 0;
}

.filters li {
  display: inline;
}

.filters li a {
  color: inherit;
  margin: 3px;
  padding: 3px 7px;
  text-decoration: none;
  border: 1px solid transparent;
  border-radius: 3px;
}

.filters li a:hover {
  border-color: #db7676;
}

.filters li a.selected {
  border-color: #ce4646;
}

.clear-completed,
html .clear-completed:active {
  float: right;
  position: relative;
  line-height: 19px;
  text-decoration: none;
  cursor: pointer;
}

.clear-completed:hover {
  text-decoration: underline;
}

.info {
  margin: 65px auto 0;
  color: #4d4d4d;
  font-size: 11px;
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
  text-align: center;
}

.info p {
  line-height: 1;
}

.info a {
  color: inherit;
  text-decoration: none;
  font-weight: 400;
}

.info a:hover {
  text-decoration: underline;
}

/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox
*/
@media screen and (-webkit-min-device-pixel-ratio: 0) {
  .toggle-all,
  .todo-list li .toggle {
    background: none;
  }

  .todo-list li .toggle {
    height: 40px;
  }
}

@media (max-width: 430px) {
  .footer {
    height: 50px;
  }

  .filters {
    bottom: 10px;
  }
}

:focus,
.toggle:focus + label,
.toggle-all:focus + label {
  box-shadow: 0 0 2px 2px #cf7d7d;
  outline: 0;
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Ⅰ. Pinia的介绍
  • Ⅱ. Pinia的使用
    • 一、例子准备
      • 1. 目标
      • 2. 效果
      • 3. 代码示例
    • 二、Pinia -- 准备store并渲染数据
      • 1. 下载pinia
      • 2. 创建pinia实例并注册
      • 3. 定义仓库
      • 4. 使用仓库
  • Ⅲ. Pinia重构待办任务案例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档