You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

非npm环境下Vue3中Pinia浏览器端引入方法咨询

在纯浏览器Vue应用中引入Pinia的完整方案

正确的CDN资源URL

你需要从unpkg引入Pinia的ES模块版本,正确的导入路径是:

import { createPinia } from 'https://unpkg.com/pinia@latest/dist/pinia.esm-browser.js'

注意:要导入createPinia而非pinia,因为需要手动创建Pinia实例并挂载到Vue应用。

完整可运行示例代码

<div id="app">
  <p>{{ message }}</p>
  <p>计数器:{{ store.count }}</p>
  <button @click="store.increment">+1</button>
</div>

<script type="module">
  // 引入Vue核心
  import { createApp, ref } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
  // 引入Pinia
  import { createPinia, defineStore } from 'https://unpkg.com/pinia@latest/dist/pinia.esm-browser.js'

  // 定义一个简单的Pinia Store
  const useCounterStore = defineStore('counter', {
    state: () => ({
      count: 0
    }),
    actions: {
      increment() {
        this.count++
      }
    }
  })

  // 创建Vue应用和Pinia实例
  const app = createApp({
    setup() {
      const message = ref('Hello Vue + Pinia!')
      // 获取store实例
      const store = useCounterStore()
      return {
        message,
        store
      }
    }
  })

  // 挂载Pinia到Vue应用
  const pinia = createPinia()
  app.use(pinia)

  // 挂载应用到DOM
  app.mount('#app')
</script>

关键步骤说明

  • 必须通过app.use(pinia)将Pinia实例注入Vue应用,否则无法使用Store
  • 使用defineStore定义Store,在组件的setup函数中调用该方法获取Store实例
  • 示例中的计数器功能可以直接在浏览器中打开运行,无需本地服务器或npm依赖

内容的提问来源于stack exchange,提问作者wagoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 14:13:15