Search code examples
vuejs3pinia

What is the proper way to assign static asset paths in a pinia store to use in component templates


I have a website I am making that may be used for other companies of mine and realistically I want to keep certain branding stuff in a single Pinia Store so I can use these variables later globally. My pinia store is as follows:

//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/')
  const companyLogoLink = ref('~assets/imgs/company-logo.png')

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

When trying to use the companyLogoLink it cannot find the image path however if I used that string directly in my template it would work and find the image. So I am wondering what would be the best way to do this?


Solution

  • You can import your assets to get its public URL

    import companyLogoLink from '@/assets/imgs/company-logo.png'
    
    export const useCompanyInfoStore = defineStore('companyInfo', () => {
      return {companyLogoLink}
    })
    
    

    Then you can use the link anywhere like so:

    const store = useCompanyInfoStore()
    console.log('this is your link', store.companyLogoLink)
    

    Note that, to use ~ or @ in the file path, you need to config vite alias like so:

    // vite.config.js
    export default defineConfig({
      resolve: {
        alias: {
          '@': path.resolve(__dirname, './src'),
        },
      }
    })