SoFunction
Updated on 2025-04-05

Solve the problem of errors when initializing the src attribute value of the dynamic binding image in vue2.0

In vue2.0, you often use syntax like this v-bind:src = "imgUrl " (abbreviation:src = "imgUrl ") to see a case

<template>
  <div>
    <img :src="imgUrl">
  </div>
</template>
<script>
export default {
  data(){
    return {
      captcha_id: "" 
    }
  },
  computed: {
    imgUrl(){
      return ' /static/ '+ this.captcha_id + '.png'
    },
  },
  methods: {
    init(){
        // A request is omitted here, assuming that the data returned successfully is res        this.captcha_id = .captcha_id;
    },
  }  
  created(){
    ();
  }
}
</script>
<style lang="scss" scoped>
</style>

As in the above case, since the data field captcha_id needs to be obtained through a network request, the page is likely to have been rendered, resulting in a 404 error every time it is loaded.

The src attribute value of the image is parsed as ' /static/.png' when initialized.

The solution is as follows:

computed: {
    imgUrl(){
      if(this.captcha_id){
        return this.$ +'/v1/cmn/captcha/new/' + this.captcha_id + '.png'
      }else{
        return null;
      }
    },
  },

The above article solves the problem of errors in the initialization of the src attribute value of the dynamic binding image of vue2.0. This is all the content I share with you. I hope you can give you a reference and I hope you can support me more.