自定义指令

suaxi
2022-05-26 / 0 评论 / 59 阅读 / 正在检测是否收录...

语法:

  1. 局部指令

    new Vue({
        directives: {指令名:配置对象}
    })
    或
    new Vue({
        directives: {指令名:回调函数}
    })
  2. 全局指令

    Vue.directive(指令名,配置对象)
    或
    Vue.directive(指令名,回调函数)

配置对象中常用的三个回调:

  1. bind:指令与元素成功绑定时调用
  2. inserted:指令所在元素被插入页面时调用
  3. update:指令所在的模板被重新解析时调用

注:

  1. 指令定义时不加 v-,但使用时要加 v-
  2. 指令名如果是多个单词,要使用kebab-case(短横杠)命名方式,不使用camelCase命名方式
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自定义指令</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!--
需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数据放大10倍
需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点
-->
<div id="root">
    <h3>当前的n值是:<span v-text="n"></span></h3>
    <h3>放大10倍后的n值是:<span v-big="n"></span></h3>
    <!-- 多个单词命名方式 -->
    <!-- <h3>放大10倍后的n值是:<span v-big-number="n"></span></h3> -->
    <button @click="n++">点我n+1</button>
    <hr>
    <input type="text" v-fbind:value="n">
</div>

<script type="text/javascript">
    //关闭开发环境提示
    Vue.config.productionTip = false
    //自定义全局指令
    Vue.directive('fbind', {
        //指令与元素成功绑定时调用
        bind(element, binding) {
            console.log('bind', this) //此处的this是window
            element.value = binding.value
        },
        //指令所在元素被插入页面时调用
        inserted(element) {
            console.log('inserted')
            element.focus()
        },
        //指令所在的模板被重新解析时调用
        update(element, binding) {
            console.log('update')
            element.value = binding.value
            element.focus()
        }
    })

    //创建Vue实例
    new Vue({
        el: '#root',
        data: {
            n: 1
        },
        directives: {
            //big函数什么时候被调用?
            //1.指令与元素成功绑定时
            //2.指令所在的模板被重新解析时
            big(element, binding) {
                element.innerText = binding.value * 10
            },
            /* 'big-number'(element,binding) {
                element.innerText = binding.value * 10
            }, */
            /* fbind: {
                //指令与元素成功绑定时调用
                bind(element, binding) {
                    console.log('bind', this) //此处的this是window
                    element.value = binding.value
                },
                //指令所在元素被插入页面时调用
                inserted(element) {
                    console.log('inserted')
                    element.focus()
                },
                //指令所在的模板被重新解析时调用
                update(element, binding) {
                    console.log('update')
                    element.value = binding.value
                    element.focus()
                }
            } */
        }
    })
</script>
</body>
</html>
0

评论 (0)

取消