1. 程式人生 > >Vue 自定義指令練習

Vue 自定義指令練習

otto inpu function pin alert check 自定義 asc rip

Vue.directive(id,definition)註冊一個全局自定義指令,接收兩個參數,指令ID以及定義對象

取值:

 <div v-demo="{ color: ‘white‘, text: ‘hello!‘ }"></div>

Vue.directive("demo", function (el, binding) {
        alert(binding.value.color);
        alert(binding.value.text);
    })

實例:

用自定義指令實現全選和取消全選
<div id="app">
    <ul>
        <li v-for
="item in list"> <input type="checkbox" v-sel="item.checked" /> {{item.name}} </li> </ul> <br /> {{list}} <br /> <button v-on:click="clickall(true)">全選</button> <button v-on:click="clickall(false)">取消全選</button> </div> <script type="
text/javascript"> Vue.directive("sel", function (el, v) { if (v.value) { $(el).attr("checked", "checked"); } else { $(el).removeAttr("checked"); } }); var vm = new Vue({ el: "#app", data: { list: [{ name:
"足球", checked: true }, { name: "籃球", checked: false }, { name: "乒乓球", checked: true }] }, mounted:function() { } , methods: { clickall: function (flag) { if (flag) { this.list.forEach(function (v, i) { v.checked = true; }); } else { this.list.forEach(function (v, i) { v.checked = false; }); } } } }); </script>

高級功能:

    <div v-pin:true.left.bottom="true"></div>



   Vue.directive("pin", function (el, binding) {

        var pinned = binding.value;//取引號中的值
        var warning = binding.arg;//取:後面的值
        var position = binding.modifiers;//取.後頁的參數

        for (var key in position){
            if (position[key]) {
                el.position[key] = 10px;
            }
        }
    });

Vue 自定義指令練習