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

如何在Pinia Store中正确配置静态资源路径以用于Vue组件模板?

解决Pinia Store中图片路径无法加载的问题

问题核心在于Pinia的JS代码里直接写的路径字符串不会被构建工具(Vite/Webpack)自动解析,但Vue模板中的路径会被编译器处理。模板里的~assets/...能正常工作,是因为Vue会自动把这个别名转换为实际文件路径,而JS字符串里的内容不会触发这个解析过程。

下面是两种可行的解决方法:

方法1:通过import引入图片资源

直接在Store中import图片文件,构建工具会自动处理路径并生成正确的资源URL:

//using composition api in Pinia
import {ref} from 'vue'
import { defineStore } from 'pinia';
// 直接import图片,构建工具会解析路径
import companyLogo from '~/assets/imgs/company-logo.png'

export const useCompanyInfoStore = defineStore('companyInfo', () => {
  const facebookLink = ref('https://www.facebook.com/blah/')
  const googleLink = ref('https://www.google.com/maps/place/blah')
  const instagramLink = ref('https://www.instagram.com/blah/')
  // 把import后的资源赋值给ref
  const companyLogoLink = ref(companyLogo)

  return {facebookLink, googleLink, instagramLink, companyLogoLink}
})

方法2:使用构建工具的动态路径解析(以Vite为例)

如果使用Vite,可以通过new URL()结合import.meta.url来动态解析路径,确保构建工具能识别并处理别名:

//using composition api in Pinia
import {ref} from 'vue'
import { defineStore } from 'pinia';

export const useCompanyInfoStore = defineStore('companyInfo', () => {
  const facebookLink = ref('https://www.facebook.com/blah/')
  const googleLink = ref('https://www.google.com/maps/place/blah')
  const instagramLink = ref('https://www.instagram.com/blah/')
  // 用new URL解析路径,Vite会自动处理~别名
  const companyLogoLink = ref(new URL('~/assets/imgs/company-logo.png', import.meta.url).href)

  return {facebookLink, googleLink, instagramLink, companyLogoLink}
})

注意:确保你的Vite配置文件中已经正确配置了~的路径别名,比如在vite.config.js里添加:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '~': path.resolve(__dirname, 'src')
    }
  }
})

之后在模板中使用companyLogoLink时,直接绑定到src属性即可:

<template>
  <img :src="companyLogoLink" alt="Company Logo">
</template>

<script setup>
import { useCompanyInfoStore } from '@/stores/companyInfo'
const companyStore = useCompanyInfoStore()
const { companyLogoLink } = companyStore
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:35:15