zoukankan      html  css  js  c++  java
  • vue2.0动态绑定图片src属性值初始化时报错

    在vue2.0中,经常会使用类似这样的语法 v-bind:src = " imgUrl "缩写 :src = " imgUrl "),看一个案例

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

    如以上案例,由于数据字段 captcha_id  需要通过网络请求取得,而页面很可能已经渲染完成,结果导致每一次加载都会出现404错误,

    其中图片的src属性值初始化时被解析为  ' http://www.demo.com/static/.png'  。

    解决方式如下:

    computed: {
            imgUrl(){
                if(this.captcha_id){
                    return this.$store.state.cmnUrl +'/v1/cmn/captcha/new/' + this.captcha_id + '.png'
                }else{
                    return null;
                }
            },
        },
  • 相关阅读:
    微信公众平台开发(51)会员卡
    iOS UIViewController的瘦身计划
    NSProxy
    Xcode
    NSPredicate
    NSArray、NSDictionary
    iOS Runtime
    iOS UmbrellaFramework
    iOS UmbrellaHeader
    iOS OCR
  • 原文地址:https://www.cnblogs.com/hcxy/p/7563438.html
Copyright © 2011-2022 走看看