Vue- directive自定义指令

官方定义:

除了核心功能默认内置的指令 (v-model 和 v-show),Vue 也允许注册自定义指令。注意,在 Vue2.0 中,代码复用和抽象的主要形式是组件。然而,有的情况下,你仍然需要对普通 DOM 元素进行底层操作,这时候就会用到自定义指令。举个聚焦输入框的例子,如下:

 <div id="root">
        <input type="text" v-sb>
    </div>
    <script src="https://juejin.cn/post/js/vue.min.js"></script>
    <script>
        // 需求:当页面加载时候,光标停在输入框内
        Vue.directive('sb', {
            // 当被绑定的元素插入到dom中时候
            inserted: function (el) {
                // 聚焦元素
                el.sb()
            }
        })
        new Vue({
            el: '#root',

        })
    </script>:
复制代码

写个loading。。。。不要问我原理,我是个菜鸡。。。

  <!-- 手写loading -->
    <div id="root">
        <div v-loading="isLoading">{{data}}</div>
        <button @click="update">更新</button>
    </div>

    <script>
        Vue.directive('loading', {
            update(el, binding, vnode) {
                // console. log( binding)
                if (binding.value) {
                    //让遮罩出来 你有没有遮罩? ? ?
                    const div = document.createElement('div')
                    div.innerText = '加载中....'
                    // 设置标识,方便删除
                    div.setAttribute('id','loading')
                    div.style.position = 'absolute'
                    div.style.left = 0
                    div.style.top = 0
                    div.style.width = '100%'
                    div.style.height = '100% '
                    //让文字居中
                    div.style.display = 'flex'
                    div.style.justifyContent = 'center'
                    div.style.alignItems = 'center'
                    div.style.color = 'white '
                    div.style.background = 'rgba(0,0,0,0.7)'
                    document.body.append(div)
                    // 怎么让遮罩消失-删除节点
                }else{
                    document.body.removeChild(document.getElementById("loading"))
                }
            }
        })
        new Vue({
            el: "#root",
            data() {
                return {
                    data: '',
                    isLoading: false
                }
            },
            methods: {
                update() {
                    this.isLoading = true
                    setTimeout(() => {
                        // 遮罩消失,数据现形
                        this.isLoading = false
                        this.data='这是后端请求的数据'
                    }, 3000)
                }
            }
        })
    </script>
复制代码

掘金有更新功能,以后成大佬了,会回来把文章完善的

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享