vue2.0异步组件?

问题描述:目标是路由页加载前,可根据需求先显示loading或者骨架屏组件。但目前这种写法直接显示路由页。求正解!!!

router.js

import asyncComponent from "@/utils/asyncLoadComponent";

const clientRoutes = [

{

path:/add",

name: 'add',

component: asyncComponent.loading(() => import("@/views/add.vue")),

meta: {

title: ‘编辑’

}

},

{

path: “/detail",

name: 'detail',

component: asyncComponent.loading(() => import("@/views/detail.vue")),

meta: {

title: ‘详情’

}

}

]

asyncLoadComponent.js

import loadComponent from "@/components/Loading";

import skeletonComponent from "@/components/Skeleton";

import errorComponent from "@/components/Error;

const loading = asyncFun => {

const com = () => ({

component: asyncFun(),

loading: loadComponent,

error: errorComponent,

delay: 1000,

timeout: 3000

});

return {

render(h) {

return h(com);

}

};

};

const skeleton = asyncFun => {

const com = () => ({

component: asyncFun(),

loading: skeletonComponent,

error: errorComponent,

delay: 1000,

timeout: 3000

});

return {

render(h) {

return h(com);

}

};

};

export default {

loading,

skeleton

}


回答:

你的代码实现有一个小问题,你需要将组件包装在 Vue.component() 中。以下是修复后的 asyncLoadComponent.js代码你可以参考一下:

import Vue from 'vue';

import loadComponent from "@/components/Loading";

import skeletonComponent from "@/components/Skeleton";

import errorComponent from "@/components/Error";

const loading = asyncFun => {

const com = () => ({

component: asyncFun(),

loading: loadComponent,

error: errorComponent,

delay: 1000,

timeout: 3000

});

return Vue.component('AsyncComponent', {

functional: true,

render(h, { data, children }) {

return h(com, data, children);

}

});

};

const skeleton = asyncFun => {

const com = () => ({

component: asyncFun(),

loading: skeletonComponent,

error: errorComponent,

delay: 1000,

timeout: 3000

});

return Vue.component('AsyncComponent', {

functional: true,

render(h, { data, children }) {

return h(com, data, children);

}

});

};

export default {

loading,

skeleton

};

请留意,我在 return 语句中添加了 Vue.component()。同时,我将组件定义为 functional 组件,这意味着它不会有自己的状态,并且渲染函数只需关注输入数据。现在,你的异步组件应该可以在路由页面加载时正确显示 loading 组件了。不过,你可能需要根据实际情况调整 delay 和 timeout 的值,方便在加载过程中更好地展示 loading 组件。

以上是 vue2.0异步组件? 的全部内容, 来源链接: utcz.com/p/934019.html

回到顶部