编写一个常用sfc组件,利用Vue.extend去new出实例并调用实例上面的方法
/*
* @Author: zhengzhiwei
* @Description: 函数式组件编写,调用及加载
*/
import Vue from 'vue'
import OrgTreeDialog from './index.vue'
export default class JsOrgTreeDialog {
instance = null
options = {}
constructor(options = {}) {
const OrgTreeDialogConstructor = Vue.extend(OrgTreeDialog)
this.instance = new OrgTreeDialogConstructor()
this.options = options
}
handlerOpen(orgTreeList = [], defaultCheckedKeys = [], callback = (nodeList) => {}) {
if (this.instance) {
document.body.appendChild(this.instance.$mount().$el)
this.instance.open(orgTreeList, defaultCheckedKeys, this.options, callback)
}
}
}
src模板代码
/* * @Author: zhengzhiwei * @Description: 组织选择组件 */
<template>
<div>
<el-dialog :show-close="false" :title="title" :visible.sync="dialogVisible" :width="width">
<div class="content-view-js-model">
<el-tree
ref="treeRef"
v-bind="options"
:data="datalist"
:default-checked-keys="defaultCheckedKeys"
:default-expanded-keys="defaultExpandedKeys"
:highlight-current="true"
:node-key="nodeKey"
show-checkbox
@check="handlerCheck"
></el-tree>
</div>
<span slot="footer" class="dialog-footer">
<el-button @click="handlerCancel">取 消</el-button>
<el-button type="primary" @click="handlerSubmit">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
name: 'OrgTreeDialog',
data() {
return {
selectlist: [], // 存储勾选的对象
callback: null, // 回调执行函数
options: null,
nodeKey: '',
defaultCheckedKeys: [],
dialogVisible: false,
width: '300px',
title: '',
defaultExpandedKeys: [],
datalist: [],
multiple: false // 是否多选
}
},
methods: {
handlerCheck(checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys) {
const checkedNodesData = checkedKeys['checkedNodes']
// 单选
if (!this.multiple) {
const length = checkedNodesData.length
this.selectlist = [checkedNodes]
if (length > 1) {
const setUnCheckList = checkedNodesData.filter((item) => item[this.nodeKey] != checkedNodes[this.nodeKey])
if (setUnCheckList.length > 0) {
this.$refs.treeRef.setChecked(setUnCheckList[0], false, false)
}
}
return
}
// 多选
this.selectlist = checkedNodesData
},
/**
* orgTreeList 树状数据
* 默认打开勾选的值
* new 的时候传来的配置
*/
open(orgTreeList = [], defaultCheckedKeys = [], options = {}, callback = (nodeList) => {}) {
this.callback = callback
this.width = options.width || '50%'
this.nodeKey = options.nodeKey || 'id'
this.title = options.title || '标题'
this.options = options
this.multiple = options.multiple || false
//
this.datalist = orgTreeList
this.defaultCheckedKeys = defaultCheckedKeys
//
this.dialogVisible = true
},
/**
* 点击确定按钮,触发回调
*/
handlerSubmit() {
this.callback(this.selectlist)
this.handlerCancel()
},
/**
* 点击取消按钮,关闭弹窗
*/
handlerCancel() {
this.dialogVisible = false
}
}
}
</script>
<style scoped lang="scss">
.content-view-js-model {
height: 60vh;
overflow: auto;
}
</style>