0
点赞
收藏
分享

微信扫一扫

【Vue】自定义指令

zhyuzh3d 2022-03-19 阅读 90
vue.js

自定义指令

Vue模板语法有2大类:
1.插值语法:
功能:用于解析标签体内容
写法:{{xxx}},xxx是js表达式,且可以直接读取到data中的所有属性。
2.指令语法:
功能:用于解析标签(包括:标签属性、标签体内容、绑定时间…)。
举例:v-bind:href=“xxx”或简写为:href=“xxx”,xxx同样要写js表达式,且可以直接读取到data中的所有属性。
备注:Vue中有很多的指令,且形式都是:v-xxx。

定义:
1.局部指令:
new Vue({directives:{指令名:配置对象}})new Vue({directives:{指令名(){}}})
2.全局指令:
Vue.directive('指令名',{配置对象})Vue.directive('指令名',function(element,binding){});

配置对象中常用的3个问题:
1.bind:指令与元素成功绑定时调用
2.inserted:指令所在元素被插入页面时调用
3.updated:指令所在模板结构被重新解析时调用

备注:
1.指令定义时不加v-,但使用时要加v-
2.指令名如果是多个单词,要使用kebab-case命名方式,不要用camelCase命名方式

案例:

<html>
<head>
    <meta charset='UTF-8'>
    <title></title>
    <script src='https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js'></script>
</head>
<body>
    <!-- 
        需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍。
        需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点。
    -->
    <div id='root'>
        <h2>当前的n值时:<span v-text="n"></span></h2>
        <h2>放大10倍的n值时:<span v-big="n"></span></h2>
        <!-- <h2>当前的n值为:<span v-big-number="n"></span></h2> -->
        <button @click="n++">点我n++</button>
        <hr>
        <input type="text" v-fbind="n">
    </div>
</body>
<script>
    //全局写法
    Vue.directive('fbind2',{
                //当指令与元素成功绑定时
                bind(element,binding){
                    element.value = binding.value
                },
                //指令所在元素插入页面时
                inserted(element,binding){
                    element.focus()
                },
                //指令所在元素被重新解析时
                update(element,binding){
                    element.value = binding.value
                    element.focus()
                }
            });
    const vm = new Vue({
        el:'#root',
        data:{
            n:1
        },
        //局部directives
        directives:{
            //big函数何时会被调用?1.指令与元素成功绑定时(一上来)2.指令所在的模板被重新解析时
            big(element,binding){
                element.innerText = binding.value * 10;
                console.log(this)   //注意此处的this时windows
            },
            // 'big-number'(element,binding){
            //     element.innerText = binding.value * 10;
            // },
            fbind:{
                //当指令与元素成功绑定时
                bind(element,binding){
                    element.value = binding.value
                },
                //指令所在元素插入页面时
                inserted(element,binding){
                    element.focus()
                },
                //指令所在元素被重新解析时
                update(element,binding){
                    element.value = binding.value
                    element.focus()
                }
            }
        }
    })
</script>
</html>
举报

相关推荐

0 条评论