Vue自定义指令——实现tab的切换
一、不适用自定义指令实现
Tab.vue
<template>
<div>
<ul>
<li
v-for="(item, index) in arr"
:key="index"
@click="change(index)"
:class="curIndex === index ? 'activeClass' : 'liClass'"
>
{
{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
arr: ["标题1", "标题2", "标题3"],
curIndex: 0,
};
},
methods: {
change(index) {
this.curIndex = index;
},
},
};
</script>
<style>
li {
list-style: none;
display: inline-block;
border: red solid 1px;
width: 100px;
height: 40px;
line-height: 40px;
cursor: pointer;
}
.liClass {
background-color: white;
}
.activeClass {
background-color: aquamarine;
}
</style>
二、使用Vue自定义指令
第一步:创建js文件:tabChange.js
第二步:修改tab.vue文件
<template>
<div>
<ul
v-tab-change="{
className: 'liClass',
activeClass: 'activeClass',
curIndex,
}"
>
<li
v-for="(item, index) in arr"
:key="index"
@click="change(index)"
class="liClass"
>
{
{ item }}
</li>
</ul>
</div>
</template>
<script>
import tabChange from "../directives/tabChange";
export default {
directives: {
tabChange,
},
data() {
return {
arr: ["标题1", "标题2", "标题3"],
curIndex: 0,
};
},
methods: {
change(index) {
this.curIndex = index;
},
},
};
</script>
<style>
li {
list-style: none;
display: inline-block;
border: red solid 1px;
width: 100px;
height: 40px;
line-height: 40px;
cursor: pointer;
}
.liClass {
background-color: white;
}
.activeClass {
background-color: aquamarine;
}
</style>
第三步:编写模块代码:
tabChange.js:了解bind和update以及参数
export default {
//加载完成就会执行
bind(el, binding) {
console.log('el', el)
console.log('binding', binding)
},
//修改内容会执行
update(el, binding) {
console.log('el', el)
console.log('binding', binding)
}
}
tabChange.js:实现默认项的选中
export default {
bind(el, binding) {
console.log('bind:el', el)
console.log('bind:binding', binding)
const options = binding.value;
//解构赋值
const {
className, activeClass, curIndex } = options;
const children = el.getElementsByClassName(className);
children[curIndex].className += ` ${
activeClass}`;//这里需要注意两个class之间要用空格
},
update(el, binding) {
console.log('update:el', el)
console.log('update:binding', binding)
}
}
tabChange.js:实现切换
export default {
bind(el, binding) {
console.log('bind:el', el)
console.log('bind:binding', binding)
const options = binding.value;
//解构赋值
const {
className, activeClass, curIndex } = options;
const children = el.getElementsByClassName(className);
children[curIndex].className += ` ${
activeClass}`;//这里需要注意两个class之间要用空格
},
update(el, binding) {
console.log('update:el', el)
console.log('update:binding', binding)
const options = binding.value;
const oldOptions = binding.oldValue;
//解构赋值
const {
className, activeClass, curIndex } = options;
const {
curIndex: oldIndex } = oldOptions;
const children = el.getElementsByClassName(className);
children[curIndex].className += ` ${
activeClass}`;//这里需要注意两个class之间要用空格
children[oldIndex].className = `${
className}`;//在切换的同时要重新设置元素的样式
}
}
扫描二维码关注公众号,回复:
13738802 查看本文章
![](/qrcode.jpg)
以上就是Vue自定义指令的实现,关注《前端面试题》专栏。
我会将自己平时项目中常见的问题以及笔试面试的知识在CSDN与大家分享,一起进步,加油。