问题形容
vue中动静绑定类名:class的用法比拟灵便,本案例以导航菜单点击高亮为例,简略进行解说,咱们先看一下最终的效果图。
形式一(对象写法)
代码图示如下
<template> <div id="app"> <div class="nav"> <div class="item" :class="{ 'highLight': index == highLight }" v-for="(item, index) in navArr" :key="index" @click="changeHighLight(index)" > {{ item }} </div> </div> </div></template><script>export default { data() { return { navArr: ["导航一", "导航二", "导航三", "导航四", "导航五", "导航六"], highLight: 0, }; }, methods: { changeHighLight(index) { this.highLight = index; }, },};</script><style lang="less" scoped>.nav { width: 240px; height: 100%; .item { width: 100%; height: 50px; background-color: #e9e9e9; line-height: 50px; text-align: center; cursor: pointer; } .item:hover { background-color: #faf; } .highLight { background-color: #faf; }}</style>
形式二(methods写法)
代码图示如下
代码附上
<template> <div id="app"> <div class="nav"> <div class="item" :class="fn(index)" v-for="(item, index) in navArr" :key="index" @click="changeHighLight(index)" > {{ item }} </div> </div> </div></template><script>export default { data() { return { navArr: ["导航一", "导航二", "导航三", "导航四", "导航五", "导航六"], highLight: 0, }; }, methods: { fn(index) { if (index == this.highLight) { return "highLight"; } }, changeHighLight(index) { this.highLight = index; }, },};</script><style lang="less" scoped>.nav { width: 240px; height: 100%; .item { width: 100%; height: 50px; background-color: #e9e9e9; line-height: 50px; text-align: center; cursor: pointer; } .item:hover { background-color: #faf; } .highLight { background-color: #faf; }}</style>
形式三(computed写法)
计算属性的写法和methods的写法略有不同,请看正文
代码附上
<template> <div id="app"> <div class="nav"> <div class="item" :class="eee(index)" v-for="(item, index) in navArr" :key="index" @click="changeHighLight(index)" > {{ item }} </div> </div> </div></template><script>export default { data() { return { navArr: ["导航一", "导航二", "导航三", "导航四", "导航五", "导航六"], highLight: 0, }; }, computed: { /* 间接这样写就会报错: Error in render: "TypeError: _vm.eee is not a function" 计算属性和办法的写法略有不同,计算属性外面要return 一个函数*/ // eee(index){ // if(index == this.highLight){ // return "highLight" // }else{ // return "kkk" // } // } // 正确写法,如果计算属性要接管参数,要return一个函数,在这个函数外面接管参数,并return对应的值 // 如果不接管参数,间接return值即可 eee() { return (index) => { if (index == this.highLight) { return "highLight"; } }; }, }, methods: { changeHighLight(index) { this.highLight = index; }, },};</script><style lang="less" scoped>.nav { width: 240px; height: 100%; .item { width: 100%; height: 50px; background-color: #e9e9e9; line-height: 50px; text-align: center; cursor: pointer; } .item:hover { background-color: #faf; } .highLight { background-color: #faf; }}</style>
总结
:class除了上述三种写法以外,还有数组的写法、三元表达式的写法。不过我集体感觉,别的写法和上述介绍的写法都相似,举一反三。灵活运用上述三种写法,基本上能够解决绝大多数的问题场景
好忘性不如烂笔头,记录一下。最初附上vue官网文档的地址: cn.vuejs.org/v2/guide/cl…