關(guān)于自定義Vue插件的兩種常見形式

自定義的vue插件,在我的理解中,分為兩種:

1.注冊成全局組件的形式

比如,你在main,js中Vue.use(yourPlugin) 然后在你的頁面內(nèi)可以這樣使用

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

2.注冊成全局函數(shù)的形式

同樣在main.js中Vue.use(yourPlugin)
但是在你的頁面內(nèi)是使用函數(shù)的形式調(diào)用的,比如

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

第一種形式可以參考這位大大的 http://www.itdecent.cn/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)
...

使用方法放在最上面那里

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容