请老师检查下,还有对其中一小段不理解
来源:4-16 自由编程
龍巛幽
2020-09-10 15:32:20
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
#app {
text-align: center;
}
ul{
width: 400px;
border: 1px solid #eee;
margin: 30px auto;
}
ul:after{
display: block;
content: '';
visibility: hidden;
height: 0;
clear: both;
}
li{
width: 33.3333%;
padding: 5px 0;
background-color: #fff;
text-align: center;
float: left;
list-style: none;
cursor: default;
}
.actived{
background-color: #eee;
}
</style>
</head>
<body>
<div id="app">
<ul>
<li
:class="{actived:idx === index}"
v-for="(item,index) of list"
:key="index"
@click="handleClick(index)"
>{{item}}</li>
</ul>
<component :is="type"></component>
</div>
</body>
<script type="text/javascript">
Vue.component('child0', {
template:'<p>前端工程师</p>'
});
Vue.component('child1', {
template:'<p>Java工程师</p>'
});
Vue.component('child2', {
template:'<p>软件测试工程师</p>'
});
var vm = new Vue({
el: "#app",
data: {
list: ['前端工程师','Java工程师','软件测试工程师'],
type: 'child0',
idx: 0
},
methods: {
handleClick(index) {
this.idx = index;
this.type = 'child' + this.idx;
console.log(this.idx);
}
}
})
</script>
</html>
class的部分是参考同学写的,运行没问题,之前写的是(:class="this.idx === index ? 'actived' : ''")这样,就不能达到样式激活的效果,本来理解的是冒号“:”后面跟的属性,在引号里面写的就是一个js表达式,那用三元运算符把idx和index比较后获得这个样式是actived还是空是可以的,为什么不行呢?而正确的写法是把 :class= 后面的内容放在 { } 里面,这是说这个 :class= 这里是一个对象吗,对象的键是 “active”,值是表达式 “idx === index”这样吗?还是我理解错了
2回答
好帮手慕慕子
2020-09-10
同学你好,粘贴的代码中没有vue文件,老师添加后测试,代码实现是正确的。
针对同学的问题解答如下:下图所示理解是对的

如果我的回答帮助到了你,欢迎采纳,祝学习愉快~
龍巛幽
提问者
2020-09-10
额,刚刚回去看了下v-bind:class的部分,好像找到问题了,
{ } 这个大括号是 :class 的固定语法,里面的冒号前面是要添加的类名 冒号后面是一个布尔值,为true时这个类名会被添加,为false时则不会添加,所以用三元运算符应该写成(:class="{actived:idx === index ? true : false}"),这样理解对吗?
相似问题