通过js调用vue组件方法
一般情况下,引入组件是通过import引入,然后在components中注册组件,如果一个页面逻辑太复杂,同一个组件要使用多次的情况下(例如自定义一个dialog组件),通过import的方式引入就使代码的可读性变差,推荐使用js加载组件。使用场景参考element ui的message组件
主要使用到vue的extend api
js文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import Vue from 'vue'; import DialogComponent from './component'; let DialogConstructor = Vue.extend(DialogComponent); let instance;
const defaultCallback = (action, params) => { if (instance) { if (action === 'confirm') { instance.resolve(params) } else if (instance.reject && action === 'close') { instance.reject() } } }
const Dialog = (options) => { return new Promise((resolve, reject) => { instance = new DialogConstructor(); instance.action = '' for (let prop in options) { if (options.hasOwnProperty(prop)) { instance[prop] = options[prop] } } instance.callback = defaultCallback instance.resolve = resolve instance.reject = reject instance.$mount() document.body.appendChild(instance.$el); instance.show = true; }) }
export default Dialog
|
vue文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| <template> <div v-if="show" class="qrcodeViewContainer"> <div>{{title}}</div> <div>{{content}}</div> <div> <button @click="confirm">确定</button> <button @click="cancel">取消</button> </div> </div> </template>
<script> import {setClipBoard} from "@/adminCommon/util/clipBoard"; import {uGetShortUrl} from "@/adminCommon/util/short-url";
export default { props: { title: { type: String, default: '' }, content: { type: String, default: '' } }, data() { return { show: false } }, methods: { confirm() { this.close('confirm') }, cancel() { this.close('cancel') }, close(action) { this.show = false this.callback(action) } } } </script>
<style lang="scss" scoped></style>
|
调用
1 2 3 4 5 6 7
| import Dialog from './dialog' let props = {title: 'test', content: 'test'} Dialog(props).then(() => { }).catch(() => { })
|
最后更新时间: