VUE-自定义指令

除了核心功能默认内置的指令 (v-model 和 v-show),Vue 也允许注册自定义指令。注意,在 Vue2.0 中,代码复用和抽象的主要形式是组件。然而,有的情况下,你仍然需要对普通 DOM 元素进行底层操作,这时候就会用到自定义指令。举个聚焦输入框的例子,当页面加载时,该元素将获得焦点 (注意:autofocus 在移动版 Safari 上不工作)。事实上,只要你在打开这个页面后还没点击过任何内容,这个输入框就应当还是处于聚焦状态。

v-xxx

<!-- 格式v-focus -->

<div style="height: 150px;background: #CCC;margin: 5px;">

     <div style="font-size: 20px;">

         v0.v-focus 自定义指令</div>

     <hr />

     <div>

         <div>

              <input v-focus/>

         </div>

     </div>

</div>

JS代码

<script>

     // 注册一个全局自定义指令 `v-focus`

     Vue.directive('focus', {

         // 当被绑定的元素插入到 DOM 中时……

         inserted: function(el) {

              // 聚焦元素

              el.focus()

         }

     })

     new Vue({

              el: "#appVue",

              data: {

                   count: 999

              }

         }

     )

</script>

 

<!DOCTYPE html>
<html style="height: 100%;">

    <head>
        <meta charset="UTF-8">
        <script type="text/javascript" src="../lib/vue.v2.5.12.js"></script>
        <title>v-xxx</title>
    </head>

    <body style="height: 100%;">
        <style>
            .style0 {
                font-size: 25px;
                color: green;
            }
            
            .style1 {
                background: gold;
            }
        </style>
        <!-- 
            VUE指令v-xxx自定义指令
                
            REF:
                http://www.runoob.com/vue2/vue-custom-directive.html
                https://cn.vuejs.org/v2/guide/custom-directive.html
        -->
        <div id="appVue">
            <!-- 格式v-focus -->
            <div style="height: 150px;background: #CCC;margin: 5px;">
                <div style="font-size: 20px;">
                    v0.v-focus 自定义指令</div>
                <hr />
                <div>
                    <div>
                        <input v-focus/>
                    </div>
                </div>
            </div>
        </div>
        <script>
            // 注册一个全局自定义指令 `v-focus`
            Vue.directive('focus', {
                // 当被绑定的元素插入到 DOM 中时……
                inserted: function(el) {
                    // 聚焦元素
                    el.focus()
                }
            })
            new Vue({
                    el: "#appVue",
                    data: {
                        count: 999
                    },
                    methods: {
                        add: function() {
                            console.log("onClick")
                        }
                    }
                }

            )
        </script>
    </body>

</html>
View Code

 

REF:

http://www.runoob.com/vue2/vue-custom-directive.html

https://cn.vuejs.org/v2/guide/custom-directive.html

posted @ 2017-12-27 21:56  zhen-Android  阅读(300)  评论(0编辑  收藏  举报