vue实现引用同一页面,需要不用的name值

36 阅读1分钟

场景描述:列表进入新增、编辑,此页面都需要缓存用户填写的数据,由于新增和编辑是同一页面,静态设置页面的name只能是一个值,导致keep-alive在缓存时找不到相对应的值,无法缓存

方法一:将表单整体封装成一个组件,新增和编辑页面分别引入表单组件,实现了每个页面有单独的name

优点:易理解,读懂

缺点:新建的页面过多 ,都是空壳页面,浪费资源

方法二:定义一个工具方法,在router.js中引入该方法并设置对应的值

 * 将指定组件设置自定义名称
 *
 * @param {String} name 组件自定义名称
 * @param {Component | Promise<Component>} component
 * @return {Component}
 */
export function createComponent (name, component) {
    return {
        name,
        data () {
            return { component: null }
        },
        async created () {
            if (component instanceof Promise) {
            try {
                const module = await component
                this.component = module?module.default:null
            } catch (error) {
                console.error(`can not resolve component ${name}, error:`, error)
            }
    
            return
            }
            this.component = component
        },
        render (h) {
            return this.component ? h(this.component) : null
        },
    }
}


// 主要在component,name和component中的第一个值要相同
{
    path: 'addCustomers',
    component: createComponent('AddCustomers', import('@/views/company/addCustomers')),
    name: 'AddCustomers',
    meta: {
      title: '新增客户', icon: ''
    }
},
{
    path: 'addCustomers/:id?',
    component: () => import('@/views/company/addCustomers'),
    component: createComponent('UpdateCustomers', import('@/views/company/addCustomers')),
    name: 'UpdateCustomers',
    meta: { title: '编辑客户', icon: '' }
},

注意点:component中的第一个参数与name值要相同 完成!大功告成~