关于Vue自定义指令、mixin和插件的封装

19 篇文章 0 订阅
4 篇文章 0 订阅


最近由于转前端,刚好学到了Vue,写一下自己的一些心得(注:无Vue基础),博客基于Vue2.x

mixin

mixin,官方解释为混入,抽离公共逻辑,然后在适当需求下,将mixin和vue实例进行混合,达到逻辑重用的目的,官方文档全局混入

注:被混入的实例对象部分方法、数据等可能会被影响

mixin的内容和组件实例一样,组件有的配置,mixin都有,如果遇到mixin和组件实例部分属性或方法冲突,则会取组件实力的方法或属性。

全局监听scroll事件的mixin

下面这个简单的全局监听scroll事件,用于实现to-top事件的监听,如果某个页面需要实现返回顶部的功能,就可以混入这个mixin

// mixin/scroll.js
export default ref => {
    return {
        mounted() {
            this.$refs[ref].addEventListener("scroll", this.onScroll);
            this.$eventBus.on("to-top", this.toTop);
        },
        beforeDestroy() {
            this.$eventBus.off("to-top", this.toTop);
            this.$refs[ref].removeEventListener("scroll", this.onScroll);
        },
        methods: {
            onScroll(e) {
                this.$eventBus.publish("scroll", e)
            },
            toTop(px) {
                this.$refs["blogListContainer"].scrollTop = px;
            },
        }
    }
}

// use
<template>
	<div ref="container"></div>
</template>
<script>
import scrollMixin from "path/to/mixin/scroll.js"
export default {
	mixins: [scrollMixin("blogListContainer")],
}
</script>
首次加载数据的mixin

使用该mixin可以抽离组件中获取首屏加载数据的重复代码,比如列表等组件的数据获取,组件实例仅需实现获取数据的方法

export default defaultValue => {
    return {
        data() {
            return {
                loading: false,
                data: defaultValue
            }
        },
        async created() {
            this.loading = true;
            this.data = await this.fetchData(); // 需要被混入的vue实例实现fetchData方法
            this.loading = false;
        }
    }
}

扩展

Vue扩展又名插件,官方文档见插件
插件顾名思义就是对vue的扩展,包括方法、属性等

怎么用——官方
export default class Plugin {
	static install = (vue, options) => {
		  // Vue的全局方法
		  Vue.myGlobalMethod = function () {
		  }
		
		  // 自定义指令
		  Vue.directive('my-directive', {
		    bind (el, binding, vnode, oldVnode) {
		      // 逻辑...
		    }
		    ...
		  })
		
		  // 全局混入
		  Vue.mixin({
		    created: function () {
		      // 逻辑...
		    }
		    ...
		  })
		
		  // 添加实例方法
		  Vue.prototype.$myMethod = function (methodOptions) {
		    // 逻辑...
		  }
	}
}

// src/main.js
Vue.use(Plugin);
怎么用——粗暴

粗暴一点的就是直接在Vue上挂载书写代码

// src/main.js

// 自定义指令
Vue.directive('my-directive', {
   bind (el, binding, vnode, oldVnode) {
     // 逻辑...
   }
   ...
 })

// 添加实例方法
Vue.prototype.$myMethod = function (methodOptions) {
  // 逻辑...
}

全局消息弹窗

全局消息弹窗诸如ElementUI的$message$notify等,此类均是使用this.$xxx调用,实现动态创建dom。

this.$message
// 获取某个虚拟dom的真是Dom结构
function getComponentRootDom(comp, props) {
    const vm = new Vue({
        render: h => h(comp, {props})
    });

    vm.$mount();
    return vm.$el;
}

export default class UIPlugin {
    static install = (Vue, options) => {
        Vue.prototype.$message = function (methodOptions) {
            /**
             * methodOptions => { type: "success" | "info" | "error" | "warn", text: "", duration: 2000 }
             */
            if (!methodOptions.text.trim()) {
                throw new Error("text is required");
            }
            let defaultOptions = {
                type: "info",
                duration: 2000,
                text: ""
            }
            let options = Object.assign({}, defaultOptions, methodOptions);
            if (!types[options.type]) {
                throw new Error(`type "${options.type}" is not supported`);
            }
            const div = document.createElement("div");
            div.classList.add(styles.messageContainer);
            const iconDom = getComponentRootDom(Icon, { type: options.type }); // Icon组件的Dom,也可以动态创建一个标签即可
            div.innerHTML = `<span class="${styles.icon} ${styles[options.type]}">${iconDom.outerHTML}</span>
                             <div class="ellipsis">${options.text}</div>`;
            document.body.appendChild(div);
            getComputedStyle(div, null).left; // 强行让浏览器渲染一次,增加动画过渡(transition)
            div.style.opacity = "1";
            div.style.transform = `translate(-50%, 50px)`
            setTimeout(() => {
                div.style.opacity = "0";
                div.style.transform = `translate(-50%, 40px)`
                div.addEventListener('transitionend', () => {
                    div.remove(); // 移除Dom
                }, { once: true });
            }, options.duration);
        }
    }
}

// use
this.$message({
	type: "success",
	text: "some information",
	duration: 2000,
})

自定义指令

自定义指令官方文档:传送门,自定义指令我们主要关注bindinsertedunbind,当bindinserted做同一件事,可以简写为一个函数

// UIPlugin
import loading from "./directives/loading"
import lazy from "./directives/lazy"
export default class UIPlugin {
	static install = (vue, options) => {
		Vue.directive('loading', loading)
		Vue.directive('lazy', lazy)
	}
}

// setup
Vue.use(UIPlugin)

// defination of loading directive
import Loading from "@/components/Loading"
import {getComponentRootDom} from "@/util/vueUtil";
const loading = "__loading";
export default function (el, binding) {
    if (binding.value) {
        const dom = getComponentRootDom(Loading, {}) // loading组件的Dom,也可自己创建div作为loading
        dom.classList.add(loading);
        // 如果没有这个元素就插入
        if (!el.querySelector(`.${loading}`)) {
            el.appendChild(dom)
        }
    } else {
    	// 如果所绑定的值loading变了,就需要将loading效果移除
        const dom = el.querySelector(`.${loading}`);
        dom && dom.remove();
    }
}

// defination of lazy directive
import {debounce} from "@/util/dom"
import defaultImage from "@/assets/default.gif"

let images = [];

function setImage(image) {
    const rect = image.dom.getBoundingClientRect();
    const windowHeight = window.innerHeight;
    // 不在视口,显示默认图片
    if (rect.top > windowHeight || rect.top < (-rect.height || -100) && image.dom.src !== defaultImage) {
        image.dom.src = defaultImage;
    } else { // 在视口,显示真实图片
        image.dom.src = image.src;
        images = images.filter(r => r !== image)
    }
}

function setImages() {
    for (const image of images) {
        setImage(image);
    }
}

function handleScroll() {
    setImages();
}

window.on("scroll", debounce(handleScroll, 50));

export default {
    bind(el, binding) {
        images.push({
            dom: el,
            src: binding.value
        });
    },
    inserted() {
        setImages();
    },
    // 切换组件时,会有unbind的动作,将images中对应元素移除
    unbind(el) {
        images = images.filter(r => r.dom !== el);
    }
}

对比起react16.8之前的版本和vue2.x版本,两者使用起来相差不大,react更接近原生js,vue封装了更多,但是需要记忆的地方更多,而且混入和高阶组件一样,有一部分影响,例如诸如的数据和prop等,react的高阶组件会使得组件树更加庞大。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值