vue之动态切换css
vue之动态切换cssvue通过class与style绑定来动态切换css我们可以传给 v-bind:class 一个对象,以动态地切换 class:<div v-bind:class="{ active: isActive }"></div>上面的语法表示 active 这个 class 存在与否将取决于数据isActive 的 truthiness(真值true or
·
vue之动态切换css
vue通过class与style绑定来动态切换css
我们可以传给 v-bind:class 一个对象,以动态地切换 class:
<div v-bind:class="{ active: isActive }"></div>
上面的语法表示 active 这个 class 存在与否将取决于数据 isActive 的 truthiness(真值true or false)。
实例演示
代码及注释如下:
<template>
<div id="wrap" class="box">
<div
v-for="(list,index) in navLists"
:key="index"
class="nav"
:class="{ red:changeRed == index}"
@click="reds(index)"
>{{list.text}}</div>
</div>
</template>
v-for 在navLists数据中循环
:class(即v-bind:class)绑定属性red,是否生效由changeRed == index 决定
@click 点击事件,改变changeRed的值
<script>
export default {
data() {
return {
navLists: [
{
text: "首页",
},
{
text: "消息",
},
{
text: "购物车",
},
{
text: "我的",
},
],
changeRed: 0,
};
},
methods: {
reds: function (index) {
this.changeRed = index;
},
},
};
</script>
<style scoped>
.box {
-webkit-border-radius: 5px; /* 页面圆角效果处理 谷歌 */
border-radius: 5px; /* 页面圆角效果处理 火狐 */
background-clip: padding-box; /* 背景绘制区域
border-box 默认值。背景绘制在边框方框内(剪切成边框方框)。
padding-box 背景绘制在衬距方框内(剪切成衬距方框)。
content-box 背景绘制在内容方框内(剪切成内容方框)。 */
margin: 100px auto; /* 计算外边距 */
width: 350px; /* 容器宽度 */
padding: 35px 35px 15px 0px; /* 四个内边距 */
background: #fff; /* 设置背景颜色 */
border: 1px solid #eaeaea; /* 设置边框*/
box-shadow: 0 0 25px #cac6c6; /* 设置边框阴影*/
}
.nav {
line-height: 40px;
display: inline-block;
margin-left: 50px;
cursor: pointer;
}
.red {
color: red;
}
</style>
两个报错
[vue/require-v-for-key] Elements in iteration expect to have ‘v-bind:key‘ directives
该报错发生在vscode中,<li v-for="item in list">
虽然报错但是页面能正常编译显示,v-for中缺少key值,改为:
<li v-for="item in list" :key="item">
Avoid using non-primitive value as key, use string/number value instead
vue渲染报错,原因可能是key值不唯一:
v-for="(list,index) in navLists" :key="list"
改为
v-for="(list,index) in navLists" :key="index"
更多推荐
已为社区贡献2条内容
所有评论(0)