关于自定义Vue插件的两种常见形式

自定义的vue插件,在我的理解中,分为两种:

1.注册成全局组件的形式

比如,你在main,js中Vue.use(yourPlugin) 然后在你的页面内可以这样使用

<template>
  <div id="yourPage">
    <yourPlugin></yourPlugin>
  </div>
</template>

2.注册成全局函数的形式

同样在main.js中Vue.use(yourPlugin)
但是在你的页面内是使用函数的形式调用的,比如

<template>
</template>
<script>
export default {
  mounted: {
    this.$yourPlugin.show({ yourData })
  }
}
</script>

第一种形式可以参考这位大大的 http://www.jianshu.com/p/d6855556cd75

主要记录一下第二种
js文件修改为

import temp from './temp.vue'
const pluginModel= {
  install (Vue, options) {
    // Vue.component(temp.name, temp)
    const Plugin= Vue.extend(temp)
    let pluginBox= document.querySelector('.plugin-box')
    function $pluginModel() {}
    $pluginModel.show = (data) => {
      return new Promise((resolve) => {
        if (!pluginBox) {
          pluginBox= new Plugin()
          pluginBox.$mount()
          document.querySelector('body').appendChild(pluginBox.$el)
        }
        pluginBox.show(data)
        resolve()
      })
    }
    Vue.prototype.$pluginModel= $pluginModel
  }
}

export default pluginModel

vue文件基本不变

<template lang="html" name="fade">
  <div class="plugin-box" v-if="isShow" @click="hide">
    <h1>瞧一瞧看一看啦哈</h1>
  </div>
</template>

<script>
export default {
  name: 'plugin',
  data () {
    return {
      isShow: false
    }
  },
  methods: {
    show: function (data) {
      this.isShow= true
    },
    hide: function () {
      this.isShow= false
    }
  }
}
</script>

<style lang="css">
</style>

然后在main.js中引入js文件并Vue.use(yourPlugin)

...
import yourPlugin from './yourPlugin.js'
Vue.use(yourPlugin)
...

使用方法放在最上面那里

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 我喜欢你 简单自然 我想认真的生活 抛却那些躁动不安 最终过上闲云野鹤的日子 读书 养花 泡奶茶
    小小山月阅读 177评论 1 2
  • 跟一个老师交流,分享在我家儿子出生前怀过一次孕,诉说的原因是因为当时的政策原因不能生下孩子,因此很自然的做了...
    郭云若阅读 678评论 0 6
  • 本文参加#感悟三下乡,青春筑梦行#活动,本人承诺,文章内容为原创,且未在其他平台发表过。 孝妇河发源于...
    文轩Fanny阅读 798评论 0 1