Skip to content

自定义指令的两种方式

  1. 函数式
  2. 对象式
html
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue</title>
    <script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/vue/2.6.14/vue.js"
        type="application/javascript"></script>
</head>

<body>
    <div id="root">
        <h2>当前n值是:<span v-text="n"></span></h2>
        <h2>放大10倍后的n值是:<span v-big="n"></span></h2>
        <button @click="n++">加n</button>
        <hr>
        <input type="text" v-fbind:value="n">
    </div>
    <script>
        Vue.config.productionTip = false;
        const vm = new Vue({
            el: '#root',
            data: {
                n: 1
            },
            directives:{
                // big函数何时会被调用
                // 1. 指令与元素成功绑定时(一上来),
                // 2. 指令所在的模板被重新解析时。
                big:function(element,binding){
                    console.log(element,binding)
                    element.innerHTML = binding.value*10
                },
                fbind:{
                    // 当指令和元素成功绑定时调用函数
                    bind(element,binding){
                        element.value = binding.value
                    },
                    // 当指令所在元素被插入页面时被调用
                    inserted(element,binding){
                        element.focus()
                    },
                    // 模板被更新时被调用了
                    update(element,binding){
                        element.value = binding.value
                    }
                }
            }
        })
    </script>
</body>

</html>

对象式更加灵活,可控制在不同的时间运行需要的程序

注意点:自定义命名只能小写,多个单词用-分隔

定义全局指令

html
Vue.directive('find2', {
    // 当指令和元素成功绑定时调用函数
    bind(element, binding) {
        element.value = binding.value
    },
    // 当指令所在元素被插入页面时被调用
    inserted(element, binding) {
        element.focus()
    },
    // 模板被更新时被调用了
    update(element, binding) {
        element.value = binding.value
    }
})
Vue.directive('find3',function(){
    // 代码
})