vue拿来写插件,会不会太那啥?
请跟我念,“不会,相符营业需求才是你的老板最想要的。”
怎样封装一个能够全局挪用的vue插件
其道理实在相称简朴,经由过程new Vue(vueComponentConstructor)您能够轻松的竖立一个vue实例,在该实例上您能够操纵要领、操纵数据、监听数据变化,运用种种钩子,对开发者而言并没有任何障碍。
我们临盆了一个实例后该怎样操纵
请跟我来,写一个完成。起首,我们先写一个vue组件。
// vue组件 A.vue
<template>
<el-dialog title="挑选文件夹" :visible.sync="visible" @close="close">
<div class="dirtree">
<el-tree
:props="dirtree"
:load="loadDir"
:render-content="refresh"
:expand-on-click-node="false"
@node-click="selectDir"
lazy
>
</el-tree>
</div>
<el-button type="success" @click="ensureSelectedDir">肯定</el-button>
<el-button @click="cancelSelectedDir">作废</el-button>
</el-dialog>
</template>
<script>
import api from '@/api'
export default {
data () {
return {
dirtree: {
label: function (data, node) {
return data.name
},
data: null,
isLeaf: true
},
visible: false,
selectedDir: ''
}
},
methods: {
close () {
this.$nextTick(() => {
// 封闭时烧毁元素
this.$destroy(true)
this.$el.parentNode.removeChild(this.$el)
})
},
ensureSelectedDir () {
},
cancelSelectedDir () {
},
selectDir (data) {
},
refreshDirData ($event, ctx) {
},
loadDir (node, resolve) {
},
refresh (h, ctx) {
}
}
}
</script>
固然,如果您的构建体系不支持vue-loader和webpack,您也能够运用以下写法
export default const Dialog = {
name: 'xxx',
template: `
<div>
// some template
</div>
`,
data () {
return {}
},
methods: {}
}
第二步,临盆api出口
// 天生挪用要领
import Vue from 'vue'
import A from './A.vue'
let AConstructor = Vue.extend(A)
export default function (options = {}) {
let instance = new AConstructor({
data: options // 混入初始化数据,也能够直接经由过程merge的体式格局把数据插进去实例对象上
})
instance.vm = instance.$mount()
document.body.appendChild(instance.vm.$el)
instance.vm.visible = true // 一些天生后的data成员操纵
return instance.vm
}
您能够将其天生单一实例,也能够每次挪用天生差别实例,在封闭时挪用$destroy合营destroyed或许beforeDestroy对存在页面上的vm.$el举行烧毁。
一些提醒
您能够将实例援用挂载到任何您想挂载的处所轻易挪用,您也能够运用Promise合营vue实例里的自定义要领或许其他要领完成promise链或许async await的天真写法。这都取决于您。