组件中的变化
一、组件中的变化
1、路由router
使用npm i vue-router@next
安装新的vue路由
接下来我们对比下vouter前后的变化:
//vue3中
//router/index
import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/Home.vue"
import About from "../views/About.vue"
const routes = [
{
path: "/",
component: Home,
},
{
path: "/about",
component: About,
},
];
export default createRouter({
history: createWebHistory(),
routes,
});
//src/main.js
import router from "./router";
createApp(App).use(router).mount("#app");
//vue2中
//src/router/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import login from '@/views/login/index.vue';
import logon from '@/views/logon/index.vue';
Vue.use(VueRouter);
const routes = [
{
path: '/login',
component: login,
},
{
path: '/logon',
component: logon,
}
];
export default router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
});
//src/main.js
import router from './router';
new Vue({
router,
render: (h) => h(App),
}).$mount('#app');
2、异步组件
//vue3
import { defineAsyncComponent } from "vue";//异步组件方法,和构造器
import { delay } from "../util";//模拟延迟
import Loading from "../components/Loading.vue";//加载时显示组件
import Error from "../components/Error.vue";//加载出错显示组件
const Block3 = defineAsyncComponent({
loader: async ()=> {
await delay();//模拟延迟加载
return import("../components/Block3.vue")
},
loadingComponent: Loading,//加载过程显示的组件
errorComponent: {//加载出错显示组件
render() {
return h(Error, "异步组件加载出错!!");利用构造函数传参
}
}
})
export default {
components: {
Block3
}
};
在浏览器中可以看到Block3的确是最后一个加载。
//vue2的异步组件就是常说的不点击不加载等。
<template>
<div class="home">
<button @click="toggleAbout">toggleAbout</button>
<button @click="toggleMy">toggleMy</button>
<Component :is="currentComponent"></Component>
</div>
</template>
<script>
export default {
name: 'Home',
data () {
return {
currentComponent: 'about'
}
},
components: {
// 异步组件引入方式,异步组件:只有在需要去展示这个组件的时候,才会把这个组件进行渲染
about: () => import('./About'),
my: () => import('./My')
},
methods: {
toggleAbout () {
this.currentComponent = 'about'
},
toggleMy () {
this.currentComponent = 'my'
}
}
}
</script>
另外博主将该文章的demo上传到了博主的资源中,欢迎下载。