如何向卡片中的图像 link 添加变量(vue-bootstrap)?
How can I add a variable to an image link in a card (vue-bootsrap)?
我正在尝试将从 API 获取的 ID 添加到图像 url 的末尾,以便循环中的每张卡片都是不同的图像。我认为 img-src 可能只接受一个字符串,而 v-bind 只接受一个属性
<b-card
class="sCardCourse m-3"
v-bind:header="course.title"
v-for="course in courses"
:key="course.id"
overlay
img-src="https://picsum.photos/500/300/?image=26"
img-alt="Card Image"
header-class="text-center headHeight"
>
<div class="sbtn">
<b-button class="fbtn" :to="{ name: 'viewCourse', params: { id: course.id}}" variant="warning">View</b-button>
<b-button :to="{ name: 'editCourse', params: { id: course.id}}" variant="warning">Edit</b-button>
</div>
</b-card>
我试过了:
在末尾加上一个+(错误说+不被接受)
添加 {{course.id}} 代替 url 末尾的静态数字(错误说明
属性内的插值已被删除并使用 v-bind 或
:id)
使用 v-bind:在 img-src 上(错误说 v-bind 需要一个属性)。
在末尾添加 {{v-bind:course.id}}(与 {{course.id}} 相同的错误)
是否可以使用 img-src 属性,或者我必须以不同的方式来做?
问题
这里的问题是,使用 v-bind 指令(缩写为冒号),引号之间的行被解析为 Javascript。这意味着您需要一对不同的引号来表示一个字符串并将一个变量连接到它。
img-src="without v-bind this is just text" // OK
:img-src="with v-bind this is javascript so it gives an error" // NOT OK
:img-src="'with v-bind and single quotes this is a valid javascript string'" // OK
解决方案
使用模板文字:
:img-src="`https://picsum.photos/500/300/?image=${course.id}`"
使用带连接的字符串:
:img-src="'https://picsum.photos/500/300/?image=' + course.id"
我正在尝试将从 API 获取的 ID 添加到图像 url 的末尾,以便循环中的每张卡片都是不同的图像。我认为 img-src 可能只接受一个字符串,而 v-bind 只接受一个属性
<b-card
class="sCardCourse m-3"
v-bind:header="course.title"
v-for="course in courses"
:key="course.id"
overlay
img-src="https://picsum.photos/500/300/?image=26"
img-alt="Card Image"
header-class="text-center headHeight"
>
<div class="sbtn">
<b-button class="fbtn" :to="{ name: 'viewCourse', params: { id: course.id}}" variant="warning">View</b-button>
<b-button :to="{ name: 'editCourse', params: { id: course.id}}" variant="warning">Edit</b-button>
</div>
</b-card>
我试过了:
在末尾加上一个+(错误说+不被接受)
添加 {{course.id}} 代替 url 末尾的静态数字(错误说明 属性内的插值已被删除并使用 v-bind 或 :id)
使用 v-bind:在 img-src 上(错误说 v-bind 需要一个属性)。
在末尾添加 {{v-bind:course.id}}(与 {{course.id}} 相同的错误)
是否可以使用 img-src 属性,或者我必须以不同的方式来做?
问题
这里的问题是,使用 v-bind 指令(缩写为冒号),引号之间的行被解析为 Javascript。这意味着您需要一对不同的引号来表示一个字符串并将一个变量连接到它。
img-src="without v-bind this is just text" // OK
:img-src="with v-bind this is javascript so it gives an error" // NOT OK
:img-src="'with v-bind and single quotes this is a valid javascript string'" // OK
解决方案
使用模板文字:
:img-src="`https://picsum.photos/500/300/?image=${course.id}`"
使用带连接的字符串:
:img-src="'https://picsum.photos/500/300/?image=' + course.id"