vue 插件(自己动手写一个vue插件)

// 来自vue官网描述 https://cn.vuejs.org/v2/guide/plugins.html#%E4%BD%BF%E7%94%A8%E6%8F%92%E4%BB%B6

插件通常用来为 Vue 添加全局功能。插件的功能范围没有严格的限制——一般有下面几种:

  1. 添加全局方法或者 property。如:vue-custom-element
  2. 添加全局资源:指令/过滤器/过渡等。如 vue-touch
  3. 通过全局混入来添加一些组件选项。如 vue-router
  4. 添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。
  5. 一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router

安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。

该方法需要在调用 new Vue() 之前被调用。

当 install 方法被同一个插件多次调用,插件将只会被安装一次。

自己动手写一个vue插件

MyToast.vue







index.js

import toastComponent from './MyToast.vue'

export default {
    /*
    * install function
    * @param  {Vue} Vue
    * @param  {object} options  myToast options
    */
    install(Vue, options = {}) {
        function myToast() {
          // vue.extend的源码解析 [https://www.jianshu.com/p/c268e16ffbe6](https://www.jianshu.com/p/c268e16ffbe6)

            const ToastComponentConstructor = Vue.extend(toastComponent)
            const instance = new ToastComponentConstructor({
                el: document.createElement('div')
            })
            document.body.appendChild(instance.$el)
            // setTimeout(() => { instance.show = false }, 2)
        }
        Vue.prototype.$myToast = myToast

    }
}

在vue项目的main.js中使用

import toastRegistry from './plugins/index'
Vue.use(toastRegistry)

app.vue





你可能感兴趣的:(vue 插件(自己动手写一个vue插件))