「这是我参与2022首次更文挑战的第18天,活动详情查看:2022首次更文挑战」
路由懒加载
路由懒加载也可以叫做路由组件懒加载。经过了Webpack编译打包后,每个路由组件的代码分割成一个个js文件,初始化时不会加载这些js文件,只当激活路由组件才会去加载对应的js文件。
// 在src/router/index.js中
// 配置路由的一般写法
// 1.通过import引入组件
import Home from '../views/Home.vue'
import About from '../views/About.vue'
// 2.配置路由规则
const router = new VueRouter({
routes:[
{
name: 'Home',
path: '/',
component: Home
},
{
name: 'About',
path: '/about',
component: About
}
]
})
要实现路由懒加载,则在配置路由规则的时候,需要使用import动态导入路由组件
// 在src/router/index.js中
// 给About组件设置懒加载
// 1.通过import引入组件
import Home from '../views/Home.vue'
const About = ()=> import ('../views/About.vue' /* WebpackChunkName: "about" */ )
//设置的WebpackChunkName,决定了控制台中显示的懒加载的文件名字,若不写则懒加载的文件会显示为0.js
// 2.配置路由规则
const router = new VueRouter({
routes:[
{
name: 'Home',
path: '/',
component: Home
},
{
name: 'About',
path: '/about',
component: About
}
]
})
<router-link>
的replace属性
- 给设置replace属性,控制路由跳转时操作浏览器历史记录的模式
- 浏览器的历史记录有两种写入模式,分别为push和replace,push是追加历史记录,replace是替换当前记录。路由跳转的时候默认是push
- 设置replace只会替换最近的一条记录,不影响前面push追加的记录
- 开启replace模式:
<router-link replace to="/news">点我跳转</router-link>
<!-- 完整写法为 :replace="true" ,简写为replace -->
axios优化
平常使用axios请求数据,每次都要在组件中引入,略显麻烦
把axios挂载到vue实例的原型上并配置请求根路径
在main.js中引入axios,并让其成为vue实例的原型上的一个属性,这样就可以在所有组件中通过this来访问,而不用在每个组件中一一引入
import axios from 'axios'
// 全局配置axios的请求根路径
// axios.defaults.baseURL = '请求根路径'
axios.defaults.baseURL = 'http://www.liulongbin.top:3006'
Vue.prototype.$http = axios
// 挂载到vue的原型上,在组件中要使用axios发起请求,直接调用this.$http.get/post
<script>
export default {
methods: {
async getInfo(){
const {data: res} = await this.$http.get('/api/get')
console.log(res)
},
async postInfo(){
const {data: res} = await this.$http.post('/api/post', {name='zs', age=18})
console.log(res)
}
}
}
</script>
跋尾
本篇内容就到这里了~ 我是Zeus👩🏻🚀来自一个互联网底层组装员,下一篇再见! 📖