Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

javascript - Static image src in Vue.js template

My Vue component contains some images. I want to do lazy-loading later, so I need to set the src of the images to a small image, first.

<template>
        <div v-for="item in portfolioItems">
            <a href="#{{ item.id }}">
                <img
                    data-original="{{ item.img }}"
                    v-bind:src="/static/img/clear.gif"
                    class="lazy" alt="">
            </a>
        </div>
</template>

Gives me a bunch of errors, like:

[Vue warn]: Invalid expression. Generated function body: /scope.static/scope.img/scope.clear.gif vue.common.js:1014[Vue

[Vue warn]: Error when evaluating expression "/static/img/clear.gif": TypeError: Cannot read property 'call' of undefined (found in component: )

webpack.config.js:
module.exports = {
    // ...
    build: {
        assetsPublicPath: '/',
        assetsSubDirectory: 'static'
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This solution is for Vue-2 users:

  1. In vue-2 if you don't like to keep your files in static folder (relevant info), or
  2. In vue-2 & vue-cli-3 if you don't like to keep your files in public folder (static folder is renamed to public):

The simple solution is :)

<img src="@/assets/img/clear.gif" /> // just do this:
<img :src="require(`@/assets/img/clear.gif`)" // or do this:
<img :src="require(`@/assets/img/${imgURL}`)" // if pulling from: data() {return {imgURL: 'clear.gif'}}

If you like to keep your static images in static/assets/img or public/assets/img folder, then just do:

<img src="./assets/img/clear.gif" />
<img src="/assets/img/clear.gif" /> // in some case without dot ./

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...