current position:Home>Vue dynamic loading picture problem

Vue dynamic loading picture problem

2022-04-29 04:05:02fresh_ nam


1. Preface

I'm learning vue When , Verb change img When the picture path , There are many problems , Write it down for reference


2. General situation

There is no problem writing the path directly :

<template>
  <div>
    <img src="../static/upload/slyline.jpg" alt="" />
  </div>
</template>

<script> export default {
       data() {
       return {
       imgSrc: "../static/upload/slyline.jpg", }; }, }; </script>

<style> </style>

 Insert picture description here
But most of the time, the image is dynamically rendered according to the image path , So use a dynamic approach .

3. problem

1、 Direct binding

The code is as follows :

<template>
  <img :src="imgSrc" alt="" />
</template>

<script> export default {
       data() {
       return {
       imgSrc: "../static/upload/slyline.jpg", }; } }; </script>
<style> </style>

result ( Direct assignment ):
 Insert picture description here
So it doesn't work

2.require introduce

The code is as follows :

<template>
  <div>
    <img :src="imgSrc" alt="" />
  </div>
</template>

<script> export default {
       data() {
       return {
       imgSrc: "", }; }, mounted() {
       var src = "../static/upload/slyline.jpg"; this.imgSrc = require(src); }, }; </script>

<style> </style>

But this will report an error :
 Insert picture description here
It must be written like this :

<template>
  <div>
    <img :src="imgSrc" alt="" />
  </div>
</template>

<script> export default {
       data() {
       return {
       imgSrc: "", }; }, mounted() {
       var src = "slyline.jpg"; this.imgSrc = require("../static/upload/" + src); }, }; </script>

<style> </style>

result :
 Insert picture description here
Introduce the same character , But you have to go around , It's strange. . Yes, leave a message in the comment area .

My file path
 Insert picture description here

copyright notice
author[fresh_ nam],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/118/202204280602490829.html

Random recommended