Vue自定义指令 directive

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
        <title>directives</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>
        <div id="app">
            <input type="text" v-model="test" placeholder="请输入" v-focus v-color />
        </div>
    </body>
</html>
<script type="text/javascript" charset="utf-8">
    // 注册一个全局自定义指令 `v-focus`
    Vue.directive('focus', {
        // 当被绑定的元素插入到 DOM 中时
        inserted: function(el) {
            // 聚焦元素
            el.focus()
        }
    })

    var app = new Vue({
        el: "#app",
        data: {
            test: ''
        },
        directives: {
            // 注册一个局部自定义指令 `v-color`
            color: {
                // 当被绑定的元素插入到 DOM 中时
                inserted: function(el) {
                    // 背景色为红色
                    el.style.background = "red";
                }
            }
        }
    });
</script>

猜你喜欢

转载自www.cnblogs.com/antao/p/12985510.html