DEV Community

Liam Hall
Liam Hall

Posted on • Originally published at Medium

2

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up