vue => 自定义指令

229 阅读1分钟
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
</head>

<body>

    <div id="app">
        <div v-set-color="color">{{num}}</div>
        <button @click="add">add</button>
    </div>
</body>
<script type="text/javascript">
    // Vue.directive('setColor', function (el, binding) { // 注册一个全局自定义指令 `v-set-color`
    //     el.style = 'color:' + binding.value//binding.value就是color颜色red。
    // })
    var app = new Vue({
        el: '#app',
        data: {
            num: 100,
            color: 'hotpink'
        },
        methods: {
            add() {
                this.num += 1
            }
        },
        directives: { // 这个是局部指令
            setColor: {
                // 指令的定义
                inserted: function (el, binding) {// inserted指的是被被绑定的元素插入到 DOM 中时……被调用
                    el.style = 'color:' + binding.value
                }
            }
        }
    })
</script>

</html>


只有空了的杯子才能装的下新水,所以杯子要时常清空。 人也一样, 学会忘记。忘记是,是为更好的接纳新的东西...