如何在.js文件夹中增加路由跳转及弹窗?-灵析社区

世界唯一的

想在vue项目中的utils文件夹中的.js文件增加路由跳转及弹窗该如何加? 没有在.vue页面中,在.js文件中打印router是undefined

阅读量:180

点赞量:0

问AI
// @/route/index.js const router = new VueRouter({ mode: 'history', base: '/', routes: [ { path: 'somewhere', component: somewhere, } ], }) export default router import router from '@/route' export function goSomewhere() { router.push('/somewhere') } *** 如果是想加弹窗的话可以写一个挂载方法,拿我正在用的举例: import Vue from 'vue' export const cache = new Set() export default function useDialog(component) { const div = document.createElement('div') const el = document.createElement('div') const id = 'dialog-' + Math.random() div.appendChild(el) document.body.appendChild(div) const ComponentConstructor = Vue.extend(component) return (propsData = {}, parent = undefined) => { let instance = new ComponentConstructor({ propsData, parent, }).$mount(el) const destroyDialog = () => { if (cache.has(id)) return if (instance && div.parentNode) { cache.add(id) instance.visible = false // 在关闭动画执行完毕后卸载组件 setTimeout(() => { cache.delete(id) instance.$destroy() instance = null div.parentNode && div.parentNode.removeChild(div) }, 250) } } // visible控制 if (instance.visible !== undefined) { // 支持sync/v-model instance.$watch('visible', (val) => { !val && destroyDialog() }) Vue.nextTick(() => (instance.visible = true)) } return new Promise((resolve, reject) => { // 组件内 emit done 事件表示确认 instance.$once('done', (data) => { destroyDialog() resolve(data) }) // 组件内 emit cancel 事件表示取消 instance.$once('cancel', (data) => { destroyDialog() reject(data) }) }) } } 使用用法: import AddGroupDialog from './AddGroupDialog.vue' function handleAdd() { useDialog(AddGroupDialog)({ // ...props }).then(() => { // onDone }) }, 弹窗组件: 取消 确定 import router from '@/router' export default { name: 'AddGroupDialog', data() { return { visible: false, } }, methods: { submit() { router.push('somewhere') }, close() { this.visible = false }, }, }