vue自定义指令:指定文字高亮

202 阅读3分钟

vue自定义指令:指定文字高亮

自定义指令

除了核心功能默认内置的指令 (v-model 和 v-show),Vue 也允许注册自定义指令。注意,在 Vue2.0 中,代码复用和抽象的主要形式是组件。然而,有的情况下,你仍然需要对普通 DOM 元素进行底层操作,这时候就会用到自定义指令

钩子函数

一个指令定义对象可以提供如下几个钩子函数 (均为可选):

  • bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。

  • inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。

  • update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新 (详细的钩子函数参数见下)。

  • componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用。

  • unbind:只调用一次,指令与元素解绑时调用。

指令钩子函数会被传入以下参数:

  • el:指令所绑定的元素,可以用来直接操作 DOM。
  • binding:一个对象,包含以下 property:
    • name:指令名,不包括 v- 前缀。
    • value:指令的绑定值,例如:v-my-directive="1 + 1" 中,绑定值为 2。
    • oldValue:指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
    • expression:字符串形式的指令表达式。例如 v-my-directive="1 + 1" 中,表达式为 "1 + 1"。
    • arg:传给指令的参数,可选。例如 v-my-directive:foo 中,参数为 "foo"。
    • modifiers:一个包含修饰符的对象。例如:v-my-directive.foo.bar 中,修饰符对象为 { foo: true, bar: true }。
  • vnode:Vue 编译生成的虚拟节点。移步 VNode API 来了解更多详情。
  • oldVnode:上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。

自定义指令:指定文字高亮

创建自定义指令

在项目 src 目录下创建自定义指令目录 directives ,并在目录下创建 index.js 和 directives.js 文件 在这里插入图片描述

index.js:

/*
 * @Description: 自定义指令
 */
import directives from './directives';

export default {
    install(Vue) {
        Object.keys(directives).forEach((key) => {
            Vue.directive(key, directives[key]);
        })
    },
}

directives.js:

/**
 * @desc 指定文字高亮指令
 * @param hText 需要高亮的文字
 * @param text 全部文字
 * @param color 高亮文字的颜色
 */
const textLight = {
    bind(el, binding, vnode) {
        const { value } = binding;
        if (value && typeof value === 'object') {
            const { hText, text, color } = value;
            el.innerHTML = text.replace(new RegExp(hText, 'ig'), (t) => {
                return `<span style="color: ${color}">${t}</span>`;
            });
        }
    },
    update(el, binding, vnode) {
        const { value } = binding;
        if (value && typeof value === 'object') {
            const { hText, text, color } = value;
            el.innerHTML = text.replace(new RegExp(hText, 'ig'), (t) => {
                return `<span style="color: ${color}">${t}</span>`;
            });
        }
    },
};

export default {
    textLight
};

main.js:

......

import Directives from './directives';
Vue.use(Directives);

使用自定义指令

<template>
    <div>
        <p v-textLight="{ hText: hText1, text: text, color: color }"></p>
        <p v-textLight="{ hText: hText2, text: text, color: color }"></p>
    </div>
</template>

<script>
export default {
    data() {
        return {
            hText1: '自定义指令', // 一个高亮文字
            hText2: '核心|自定义指令', // 多个高亮文字
            text: '除了核心功能默认内置的指令 (v-model 和 v-show),Vue 也允许注册自定义指令。',
            color: '#c7254e'
        }
    }
}
</script>

效果

在这里插入图片描述