自定义指令

29 阅读1分钟

指令: vue中 指令就是标签中v-开头的一种有特定功能的属性 它在vue运行了以后,就具有封装好的功能
自定义指令:自己设定想要的功能,之后在标签中直接使用v-xx(xx为自己定义的名字)即可,使用起来十分简洁

  <div id="app">
        <div v-red>{{msg}}</div>
        <div v-big="'200px'" style="background-color: aquamarine;">{{msg1}}</div>
        <input type="text">
        <input type="text" v-focus>
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                msg: "红色",
                msg1: "盒子变大"
            },
            directives: {
                red: {
                    inserted(el, option) {
                        // option:与那个指令相关的信息
                        console.log(el, option) //绑定使用这个指令的节点对象
                        el.style.color = "red"
                    }
                },
                big: {
                    inserted(el, option) {
                        console.log(el, option)
                        el.style.width = option.value
                        el.style.height = option.value

                    }
                },
                focus: {
                    inserted(el) {
                        el.focus()
                    }
                }
            },
        })
    </script>

image.png