DEV Community

Liam Hall
Liam Hall

Posted on • Originally published at Medium

Accessing Nuxt asset URL’s in custom attributes

When creating any new Nuxt project, there are a number of ways you can access static assets, though the assets folder or the static folder. These folders are treated very differently by Nuxt — Files in the assets folder will be treated as module dependancies and run through Webpack, while files in the static folder will simply be copied to the public folder. When compiling the assets folder, the URL loader will conditionally inline assets that are smaller than 4kb*, reducing the amount of HTTP requests.

By default Asset URL’s can be called as CSS imports, from within your CSS and in templates from the following attributes:

{
  video: ['src', 'poster'],
  source: 'src',
  img: 'src',
  image: 'xlink:href'
}
Enter fullscreen mode Exit fullscreen mode

However there can be situations when you may want to call an asset from a custom attribute in your template — Luckily Nuxt makes that very easy. For example, let’s say you have an icon assets/icons/ticket-icon.svg you’d like to access but you’d like to lazy load that asset as a background image on a div, by default this will not work. However, by opening up your nuxt.config.js file and navigating to build, you’re able to extend the build to instruct vue.transformAssetUrls to accept a custom attribute(s) on elements, in this case a custom background source on a div:

build: {
    extend (config, { loaders: { vue } }) {
        vue.transformAssetUrls.div = ['data-background-src']
    }
}
Enter fullscreen mode Exit fullscreen mode

In the above example vue.transformAssetUrls has a key of div (element) which accepts an array of attributes — in this case a custom data-background-src attribute. Following the above example, the assets/icons/ticket-icon.svg asset will now be available in your templates within the custom property data-background-src:

<template>
    <div class="example" data-background-src="~assets/icons/ticket-icon.svg">
        /**/
    </div>
</template>
Enter fullscreen mode Exit fullscreen mode

If you’ve found this article useful, please give it a clap and follow me on Medium, Dev.to and/ or Twitter.

Oldest comments (0)