一、背景
1.1、需求
项目:nuxt2 + vue2
希望通过编程方式的调用打开对话框,展现我们想要的内容。
1.2、效果
二、代码
2.1、插件 plugins/dialog.js
- import Vue from 'vue';
- import { Dialog } from 'element-ui';
- // 本文使用了Dialog组件,也可以使用自己开发的组件,这样就更加灵活了,根据自己的项目实际需要来定
- export default function programmingMethodToCallComponents(context, inject) {
- // context:Nuxt.js 提供的上下文对象,包括 $axios(用于 HTTP 请求)、store(Vuex 状态管理)
- // inject:用于将某些功能注入到全局上下文
- const { $axios, store, route } = context;
- const initInstance = (text, component, options = {}) => {
- const { attrs, ...otherOptions } = options;
- const instance = new Vue({
- router: store.$router,
- $axios,
- store,
- components: { CurrentComponent: component },
- data() {
- return {
- dialogVisible: false,
- };
- },
- methods: {
- open() {
- this.dialogVisible = true;
- },
- },
- render() {
- return (
- <Dialog
- ref="dialog"
- title="提示"
- visible={this.dialogVisible}
- attrs={otherOptions}
- >
- <div>{{ text }}</div>
- </Dialog>
- );
- },
- });
- instance.$mount();
- document.body.appendChild(instance.$el);
- return instance.open();
- };
- inject('dialog', initInstance);
- }
复制代码 2.2、页面利用 pages/dialog.vue
- <template>
- <div>
- <div @click="programmingMethodToCallComponents">dialog</div>
- </div>
- </template>
- <script>
- export default {
- components: {},
- data() {
- return {};
- },
- mounted() {},
- methods: {
- programmingMethodToCallComponents() {
- this.$dialog('我是dialog')
- },
- },
- };
- </script>
- <style lang="less" scoped>
- </style>
复制代码 2.3、nuxt.config.js
- plugins: [
- {
- src: '../plugins/dialog'
- }
- ]
复制代码 三、欢迎交换指正
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |