Home  >  Article  >  Web Front-end  >  Solve the problem of error when initializing the src attribute value of dynamically bound images in vue2.0

Solve the problem of error when initializing the src attribute value of dynamically bound images in vue2.0

亚连
亚连Original
2018-05-30 14:10:051713browse

Below I will share with you an article that solves the problem of error when initializing the src attribute value of vue2.0 dynamic binding image. It has a good reference value and I hope it will be helpful to everyone.

In vue2.0, syntax similar to v-bind:src = " imgUrl " (abbreviation: src = " imgUrl ") is often used. Let's look at a case.

<template>
  <p>
    <img :src="imgUrl">
  </p>
</template>
<script>
export default {
  data(){
    return {
      captcha_id: "" 
    }
  },
  computed: {
    imgUrl(){
      return &#39; http://www.demo.com/static/ &#39;+ this.captcha_id + &#39;.png&#39;
    },
  },
  methods: {
    init(){
        // 此处省略一个请求 ,假设成功返回数据为 res
        this.captcha_id = res.data.captcha_id;
    },
  }  
  created(){
    this.init();
  }
}
</script>
<style lang="scss" scoped>
</style>

In the above case, since the data field captcha_id needs to be obtained through a network request, and the page has probably been rendered, a 404 error will occur every time it is loaded.

The picture The src attribute value is parsed as 'http://www.demo.com/static/.png' when initialized.

The solution is as follows:

computed: {
    imgUrl(){
      if(this.captcha_id){
        return this.$store.state.cmnUrl +&#39;/v1/cmn/captcha/new/&#39; + this.captcha_id + &#39;.png&#39;
      }else{
        return null;
      }
    },
  },

The above is what I compiled for everyone, I hope It will be helpful to everyone in the future.

Related articles:

Vue’s browser storage method encapsulation example

Vue implements the method of exiting after prompting to save

Usage example of bootstrap-datetimepicker time plug-in in angular project

The above is the detailed content of Solve the problem of error when initializing the src attribute value of dynamically bound images in vue2.0. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn