1. 基础概念
在Vue中,你可以使用v-bind指令(简写为:)来绑定一个属性。对于img标签,我们可以绑定其src属性。
2. 示例代码
<template>
<div>
<img :src="imageUrl" alt="动态图片展示">
<button @click="changeImage">更换图片</button>
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: 'https://example.com/initial-image.jpg'
}
},
methods: {
changeImage() {
// 根据需要更换图片URL
this.imageUrl = 'https://example.com/new-image.jpg';
}
}
}
</script>
3. 动态绑定图片路径的技巧
3.1 使用变量存储图片路径
data() {
return {
imageBasePath: 'https://example.com/images/',
imageName: 'initial-image.jpg'
}
},
computed: {
imageUrl() {
return `${this.imageBasePath}${this.imageName}`;
}
}
3.2 根据条件动态切换图片
data() {
return {
userStatus: 'active'
}
},
computed: {
welcomeImage() {
return this.userStatus === 'active' ? 'welcome-active.jpg' : 'welcome-inactive.jpg';
}
}