- directives本质上可以看作为一个对象{}
- 常用的vue指令有v-if, v-for, v-show,
- 用户也可以注册自定义指令,使用钩子函数操作dom:对普通 DOM 元素进行底层操作,实际就是使用js操作dom。
- 常用的钩子函数:
bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。
- 例子: 实现点击,激活按钮(改变背景颜色)
// 在directives文件中自定义一个js文件
export default {
bind: function (el, binding) {
const { activeClass, className, curIndex } = binding.value;
const children = el.getElementsByClassName(className);
children[curIndex].className += ` ${activeClass}`;
},
update: function (el, binding) {
const { activeClass, className, curIndex } = binding.value;
const children = el.getElementsByClassName(className);
children[curIndex].className += ` ${activeClass}`;
const { curIndex: oldIndex } = binding.oldValue;
children[oldIndex].className = className
},
inserted: function (el, binding) {
el.focus();
},
};
// 在组件中注册使用
<div class="container" v-active="{ activeClass: 'btn-active', className: 'btn-main', curIndex }">
<div
v-for="(item, index) in subjects"
:key="index"
:curIndex="curIndex"
:index="index"
:item="item"
class="btn-main"
@click="handle(index)"
>
{{ item }}
</div>
</div>
<script>
import active from "@/directives/index";
export default {
name: "app",
directives: {
active, // 局部注册
},
data() {
return {
curIndex: 0,
subjects: ["vue", "react", "angular"],
};
},
methods: {
handle(index) {
this.curIndex = index;
},
},
};
</script>
- 自定义指令全局注册:
Vue.directive('focus', {
bind: function(el, binding){},
update: function(el, binding){}
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el) {
// 聚焦元素
el.focus()
}
})``js
最近这个例子复习了四个知识点:使用mixin自定义UI组件, 父子组件传值,为父组件添加事件代理,使用自定义指令动态控制样式