自定义指令

时间:2019-08-20
本文章向大家介绍自定义指令,主要包括自定义指令使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <script src="vue.js"></script>
    </head>
    <body>
        <div>
        <h1>--钩子函数参数--</h1>
        <div id="example-1" v-demo:foo.a.b="message"></div>
        <script>
        Vue.directive('demo', {
            bind: function (el, binding, vnode) {
                var s = JSON.stringify
                el.innerHTML = 
                    'name: ' + s(binding.name) + '<br>' +
                    'value: ' + s(binding.value) + '<br>' +
                    'expression: ' + s(binding.expression) + '<br>' +
                    'argument: ' + s(binding.arg) + '<br>' +
                    'modifiers: ' + s(binding.modifiers) + '<br>' +
                    'vnode keys: ' + Object.keys(vnode).join(', ')
            }
        })
        
        new Vue({
            el: '#example-1',
            data: {
                message: 'hello!'
            }
        })
        </script>
        </div>
        <div>
        <h1>--动态指令参数1--</h1>
        <div id="example-2">
            <p>Scroll down the page</p>
            <p v-pin="200">Stick me 200px from the top of the page</p>
        </div>
        <script>
        Vue.directive('pin', {
            bind: function (el, binding, vnode) {
                el.style.position = 'fixed'                
                el.style.top = binding.value + 'px'
            }
        })
        
        new Vue({
            el: '#example-2'
        })
        </script>
        </div>
        <div>
        <h1>--动态指令参数2--</h1>
        <div id="example-3">
            <p>Scroll down inside this section ↓</p>
            <p v-pin2:[direction]="200">I am pinned onto the page at 200px to the left.</p>
        </div>
        <script>
        Vue.directive('pin2', {
            bind: function (el, binding, vnode) {
                el.style.position = 'fixed'
                var s = (binding.arg == 'left' ? 'left' : 'top')
                el.style[s] = binding.value + 'px'
            }
        })
        
        new Vue({
            el: '#example-3',
            data: function () {
                return {
                    direction: 'left'
                }
            }
        })
        </script>
        </div>
    </body>
</html>

原文地址:https://www.cnblogs.com/gongshunfeng91/p/11381837.html