The vue render function dynamically loads the src path operation of img

  • 2021-09-04 23:18:06
  • OfStack

Share 1 How do I solve the problem of how to correctly configure the src path of img in vue render?

1. My project has two layers of components,

The first layer is the parent component, and the second layer is the component encapsulated by render function, and the parent component calls the render function component

2. In the render function, you need to create < img > Tag, src in img is passed in by the parent component;

src is passed in correctly, but the picture is not displayed.

3. Solutions:

First, put the picture import in the parent component.

import empty from "./img/empty.png";

Declare 1 variable in the data of the parent component to bring in the empty picture

empty: empty,

The parent component passes the picture to the child component, which is

< index-grid :empty="empty" > < /index-grid >

Subcomponents receive empty in props


props: {
  empty: {
   type: String
  }
 },

Subcomponents can use src directly


img.push(
    h("img", {
     style: {
      verticalAlign: "middle"
     },
     attrs: {
      src: empty
     }
    })
   );

Supplementary knowledge: VUE dynamically adds src to img elements and matters needing attention

In the vue project, it is usually necessary to render multiple img elements through v-for. When we want to add their own src to each img element, we need to use vue src dynamic binding

For example, the following:

< img: src= "typeIcon (tt. questionType)" alt= "Load failed" >

The tt here is the rendered content, and the src of each img needs to be judged according to the questionType of tt

We first set a function for this decision and bind it to img.


typeIcon:function(kind){
      switch (kind){
      case 1 : return require("../../assets/images/single_choice.png" )
      break;
      case 2 : return require( "../../assets/images/multi_choice.png" )   
      break;
      case 3 : return  require( "../../assets/images/matrix_single.png" )        
      break;
      case 4 : return  require( "../../assets/images/matrix_multi.png") 
      break;
      case 5 :return  require("../../assets/images/blank.png" )
      break;
      default: return   require( "../../assets/images/shortAnswer.png" )
    }
  },

Here we use an switch statement to determine the src corresponding to each img.

What should be noted here is:

To return src, you need to precede the src string with require

Finally, bind typeIcon with: src

< img: src= "typeIcon (tt. questionType)" alt= "Load failed" >


Related articles: