# vue directive -- 自定义指令
# 前言
你可能知道 directive, 但你知道过滤器, 为啥要用 directive, 需要的时候在用不香吗? 但有些全局的设置 你必须知道 在以往的开发中, 你是否会经常写出这样的代码
// 每次想要聚焦是选中所有内容
<template>
<el-input v-model="value" ref="input1" class="input-code" v-focus></el-input>
</template>
<script>
export default {
directive: {
focus: {
inserted: function (el) {
// 聚焦元素
el.querySelector('input').focus();
el.querySelector('.el-input input').focus();
},
},
},
methods: {},
};
</script>
其实, 这些也对但复用率极低, 多个地方使用了呢?
# 解决场景
- 需要在组件中引用之后, 还需要声明之后 才能使用
- 需要在每个地方专门处理一遍格式才能使用
- 加快 dom 加载速度, 不予要重复调用 js
# 抒写方式
// ======== 此处以element-ui为例
import Vue from 'vue';
Vue.directive('focus', {
inserted: function (el) {
// 聚焦元素
el.querySelector('input').focus();
el.querySelector('.el-input input').focus();
},
});
// ==== template
<el-input v-model="value" ref="input1" class="input-code" v-focus></el-input>
注意:
- 当前只是讲解其中一种, 最舒适用法的一种, 如需要了解更多, 请自行百度
- 道路千万条, 规范唯一条, 不拘泥, 你将无人能挡