vue.js - vuejs :src with a v-if condition

标签 vue.js

此代码有效,但有没有办法将这两个条件和输出合并到一行代码中?

<img v-if="pointshover" :src="pointshover" :key="pointshover" class="leaderimg">
<img v-if="!pointshover" :src="leaderPoints[0].playerimg" :key="pointshover" class="leaderimg">

基本上,如果 'pointshover' 为 null,那么它会从 leaderPoints[0].playerimg 抓取图像 src。如果 'pointshover' 不为空,则它是 src。

最佳答案

选项 1

然后,由于您只想使用一条线,因此采用@choasia 提出的解决方案并稍加改动。

<img :src="pointshover ? pointshover : leaderPoints[0].playerimg" :key="pointshover" class="leaderimg">

您不需要 v-if,因为此图像始终显示,并且只有当它存在时它才会有 pointshover src,而当它不存在时会有 leaderPoints[0].playerimg。

选项 2

如果您使用两行代码,您可能应该使用:

<img v-if="pointshover" :src="pointshover" :key="pointshover" class="leaderimg">
<img v-else :src="leaderPoints[0].playerimg" :key="pointshover" class="leaderimg">

如果你使用 else,你想要完成的事情会更清楚。

选项 3

你可以使用 computed property绑定(bind) src。

<img :src="myImageSource" :key="pointshover" class="leaderimg">

myImageSource(){
    return this.pointshover ? this.pointshover : this.leaderPoints[0].playerimg;
}

关于vue.js - vuejs :src with a v-if condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46921903/

相关文章:

javascript - 如何使用vue组件和laravel Controller 上传文件[Axios]

javascript - 如何通过应用程序使用对话框,向其传递内容

javascript - 如何正确使用 v-show 渲染我的元素?

testing - 测试时如何嵌套Vue.nextTick?

javascript - 如何在 vueJs 测试中模拟调度

javascript - 不明白用vue-cli创建的Vue项目的项目结构

laravel - 如何使用惯性 js 保留滚动按钮

jquery - 在 Vue.js 中一次选择多个图像

javascript - Vuex/Vuejs : accessing localStorage within vuex store

javascript - VueJs 选择时禁用/启用 Div