gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
vue3,<img :src="currentTab === item.name ? item.img1 : item.img2" alt=""…
- User
vue3,标签在currentTab变化之后没有动态变化src,为什么呢
- Assistant
可能是因为Vue的响应式系统没有检测到currentTab的变化,因此没有触发更新。
可以尝试使用计算属性来代替直接绑定src的方式,如下所示:
code<template> <img :src="imgSrc" alt="" /> </template> <script> export default { data() { return { currentTab: '', // 当前标签 item: { name: '', img1: '', img2: '' } } }, computed: { imgSrc() { return this.currentTab === this.item.name ? this.item.img1 : this.item.img2 } } } </script>这样,只要currentTab发生变化,imgSrc就会被重新计算,从而更新图片的src。
- User
我用的vue-class-component
- Assistant
在使用
vue-class-component时,你可以在类中定义一个计算属性来动态绑定图片的src,就像下面这样:code<template> <img :src="imgSrc" alt=""> </template> <script lang="ts"> import { Vue, Component, Prop } from "vue-property-decorator"; interface TabItem { name: string; img1: string; img2: string; } @Component export default class MyComponent extends Vue { @Prop() currentTab!: string; @Prop() item!: TabItem; get imgSrc() { return this.currentTab === this.item.name ? this.item.img1 : this.item.img2; } } </script>这里使用了ES6的计算属性语法,在
get imgSrc()方法中返回动态计算的值。你可以直接在模板中使用
imgSrc属性来绑定图片的src,无需使用三元表达式。在currentTab或item变化时,计算属性会自动更新其值并刷新视图。注意,这里使用了装饰器
@Component将类转化为Vue组件。同时,由于使用了TypeScript,需要在属性前使用装饰器@Prop()来声明其为组件的属性。