基于对象值的样式绑定



我正在尝试动态样式的基础上的口袋妖怪的类型元素(如:火得到一个火的图标,火/飞行得到1个火1个飞行)。

我试着用一个三元运算符和:style来做,但它真的很长很乱,所以我宁愿不这样做。目前,我将它设置为一个方法,并传入一个数组,如下所示:

types: ["water", "flying"] //or sometimes just one value eg: types: ['fire']
下面是我的方法:
methods: {
typeStyle: function (types) {
const backgroundImageUrls = []
for (const i in types) {
backgroundImageUrls.push('url(../assets/' + types[i] + '.svg)')
}
console.log(backgroundImageUrls)
let backgroundPosition = 'center'
if (backgroundImageUrls.length > 1) {
backgroundPosition = 'left right'
}
return {
backgroundImage: backgroundImageUrls.join(','),
backgroundPosition
}
}
}

这是HTML模板它被称为

<li
class="card"
v-for="(mon, index) in team"
:key="index"
>
<div class="cardfront-images"
:style="typeStyle(mon.types)"
>
...
</li>

但它不起作用。我还想应用第二种效果,如果有一种类型,则使用background-positionbackground-position: "center",如果有两种,则使用background-position: "left right"。但是我得到一个错误,因为在CSS属性中的连字符。

编辑

所以我有它的工作,它使url()的背景图像(耶!),但不幸的是,没有应用样式。很明显,有些东西出了问题。我还更新了我的代码块以反映更改。

EDIT2:所以这个解决方案确实有效,我已经检查了。由于某种原因,它不喜欢我的本地资产是字符串化的,所以我只是从git仓库调用图像。我想这已经足够好了,因为我做这个只是为了我自己的教育。

您可以做的是将所有后台url存储到一个数组中,然后在return语句之前加入该数组。

关于background-position属性,请记住,在JS中所有的CSS属性都是kebab大小写的,因为-会导致JS将其解释为算术运算,所以使用backgroundImage应该是实现它的方法。

假设对象的types数组中每个对象的url键包含到图像的实际路径,您可以这样做。注意,在定义Vue方法时应该避免使用箭头函数,因为函数中的this将不再引用组件实例。

new Vue({
el: '#app',
data: function() {
return {
team: [{
ability: "Keen Eye",
name: "Wingull",
id: 278,
types: [{
type: {
name: "water",
url: "http://via.placeholder.com/100x100?text=water"
},
},
{
type: {
name: "flying",
url: "http://via.placeholder.com/100x100?text=flying"
}
}
]
}]
};
},
methods: {
typeStyle: function(types) {
// Collect all URLs into an array with the template literal applied so we can use it directly in CSS
const backgroundImageUrls = types.map(entry => `url(${entry.type.url})`);
// Default value of background-position
let backgroundPosition = 'center';
if (backgroundImageUrls.length > 1) {
// Example: you want one image on the top left, and another on the top right
backgroundPosition = 'top left, top right';
}
return {
backgroundImage: backgroundImageUrls.join(','),
backgroundPosition
};
}
}
});
.cardfront-images {
width: 500px;
height: 100px;
background-repeat: no-repeat;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li class="card" v-for="(mon, index) in team" :key="index">
{{ mon.ability }}, {{ mon.name }}, {{ mon.id }}
<div class="cardfront-images" :style="typeStyle(mon.types)"></div>
</li>
</ul>
</div>

有几种不同的方法可以做到这一点:

对于条件样式,您可以使用动态类,如:

<div :class="{ mon.type }"

这将自动获取类型名('fire', 'water'等),如果你愿意,你可以在上面使用CSS。

为了正确地呈现图标,您需要对提供给它的JSON对象进行一些调整。

但是我需要知道你是否有所有可用的信息,或者你将以什么格式获取它。

当你让我知道时,我会更新我的答案。

最新更新