Vue.js 笔记之 img src

  • 固定路径(原始html)

    index.html如下,其中,引号""里面就是图片的路径地址

    ```<img src="./assets/1.png"> ```
  • 单个可变路径

    index.html如下

    ```<div id="app"> <img v-bind:src="imgSrc"> </div> ```

    对应地,app里面要有src,

    
    var app = new Vue({
            el: '#app',
            data: {
                    imgSrc: './assets/2.png'
            }
    }
    

    这样就可以通过改变imgSrc来改变某一个img标签指向的图片了

  • basePath + 参数

    比如有10张图片放在./assets/目录中,图片名1.png, 2.png ...

    Vue的文档里面有这么一句话

    Vue.js allows you to define filters that can be used to apply common text formatting.

    因此需要借助filter。html如下,其中img_id是图片名中的数字,如1,2,3... 而getImage是filter中的一个key

    ```<div id="app"> <img v-bind:src="img_id | getImage"> </div> ```

    Vue的options要添加filters

    
    var app = new Vue({
            el: '#app',
            data: {
                    imgSrc: './assets/2.png'
            },
    
            // text formatting
            filters: {
                    getImage: function(teamId){
                            return `./assets/${teamId}.png`
                    }
            },
    }
    

原文地址:https://segmentfault.com/a/1190000013090116

posted @ 2018-11-13 13:32  sfornt  阅读(2412)  评论(0编辑  收藏  举报