1. imgsrc属性简介

<img :src="imgsrc" alt="图片描述">

在这个例子中,:src就是imgsrc属性的简写形式。

2. imgsrc属性的使用场景

2.1 动态更换图片

data() {
  return {
    gender: 'male',
    imgsrc: 'https://example.com/male.jpg'
  };
},
watch: {
  gender(newVal) {
    if (newVal === 'male') {
      this.imgsrc = 'https://example.com/male.jpg';
    } else {
      this.imgsrc = 'https://example.com/female.jpg';
    }
  }
}

2.2 图片懒加载

<img :src="imgsrc" @load="handleLoad" alt="图片描述">
methods: {
  handleLoad() {
    this.imgsrc = this.imgsrc.replace('small', 'large');
  }
}

2.3 图片错误处理

<img :src="imgsrc" @error="handleError" alt="图片描述">
methods: {
  handleError() {
    this.imgsrc = 'https://example.com/default.jpg';
  }
}

3. 实战技巧

3.1 图片路径管理

// images.js
export const imgUrls = {
  male: 'https://example.com/male.jpg',
  female: 'https://example.com/female.jpg',
  default: 'https://example.com/default.jpg'
};

然后在组件中使用这个文件:

import { imgUrls } from './images';

data() {
  return {
    gender: 'male',
    imgsrc: imgUrls.male
  };
}

3.2 使用图片懒加载库

<img v-lazy="imgsrc" alt="图片描述">
import Vue from 'vue';
import VueLazyload from 'vue-lazyload';

Vue.use(VueLazyload);

4. 总结