Vue 自定义指令练习

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';
            }
        }
    });

 

posted @ 2017-09-12 22:26  lunawzh  阅读(221)  评论(0编辑  收藏  举报