vue前端路由和异步组件

161 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

路由

前端路由的目的: 在不用请求后端的情况下跳转页面

hash路由

1.通过改变hash值去改变路由 2.通过loacation.hash得到hash值 '#/curriculum' 3.监听事件: hashchange:监听hash的改变做出反应

history路由

1.通过改变hash值去改变路由
2.通过loacation.pathname得到路由 '/md/' 3.监听事件: popstate:监听浏览器操作引起的路由变化,比如浏览器的回退 4.history还有pushState和replaceState去操作路由栈去改变路由 5.history是在h5的基础上新出的,在对IE9一下的支持不如由来已久的hash 6.history需要进行一些nginx配置解决它找不到对应文件时的请求的后端的入口文件

	## history
	location / {
 		root /var/www;
 		index index.php index.html index.htm;
		try_files $uri $uri/ /index.html;
	}

异步组件

为什么使用异步组件?

由于组件过大,从后端拉取某些数据可能要耗时等待,所以我们在一定的条件或者等其他同步组件加载完成之后再异步加载过大的组件,再他加载完成后再使用。(有点类似懒加载)

如何使用异步组件?各个版本都提供了一些使用异步组件的方法 vue2.0中使用方法

vue.conponent('async-conponent1', function(resolve, reject) {
	setTimeout(function() {
	    // 向 `resolve` 回调传递组件定义
		resolve({
			template: '<div>async-conponent1</div>'
		})
	},3000)
})
vue.conponent('async-conponent2', function(resolve, reject) {
	// 这个特殊的 `require` 语法将会告诉 webpack
 	// ⾃动将你的构建代码切割成多个包,这些包
 	// 会通过 Ajax 请求加载
	require(['./my-async-component'],resolve)
})
vue.conponent('async-conponent3', () => {
	// 这个动态导⼊会返回⼀个 `Promise` 对象
	import('./my-async-component');
})

2.3.0+ 新增使用方法

const AsyncComponent = () => ({
	 // 需要加载的组件 (应该是⼀个 `Promise` 对象)
 	component: import('./MyComponent.vue'),
 	// 异步组件加载时使⽤的组件
 	loading: LoadingComponent,
	 // 加载失败时使⽤的组件
 	error: ErrorComponent,
 	// 展示加载时组件的延时时间。默认值是 200 (毫秒)
	delay: 200,
 	// 如果提供了超时时间且组件加载也超时了,
 	// 则使⽤加载失败时使⽤的组件。默认值是:`Infinity`
 	timeout: 3000
})

vue3.0中使用方法

const { createApp, defineAsyncComponent } = Vue
const app = createApp({})
const AsyncComp = defineAsyncComponent(() => 
	new Promise((resolve, reject) => {
 		resolve({
			template: '<div>I am async!</div>'
 		})
 }))
app.component('async-example', AsyncComp);
import { defineAsyncComponent } from 'vue'
const AsyncComp = defineAsyncComponent(() =>
 	import('./components/AsyncComponent.vue')
)
app.component('async-component', AsyncComp)
import { createApp, defineAsyncComponent } from 'vue'
createApp({
	 components: {
 		AsyncComponent: defineAsyncComponent(() =>
 			import('./components/AsyncComponent.vue')
 		)
 	}
})

异步组件使用时,当判断出即将加载一个异步组件,首先会放一个空node,等异步组件加载完成才将node内容加载进去。

动态组件

为什么要使用动态组件? 就是在页面层级,通过条件的限制选择去使用A组件或者B组件等。。。

异步组件和动态组件的对比

异步组件加载时首先从服务器拿到一个异步的ajax并在加载一个空node,等ajax调用完成从服务器上拉取到组件,组件加载成功后,会替换之前的空node; 而动态组件就是一开始从服务器拿到组件node,它不是从服务器去拉取组件的时机问题,而是页面上的条件是动态的,等条件满足时加载相应的组件

动态组件: /about/:id 异步组件: import('./my-async-component');