路由的使用
1.安装 vue-router : npm i vue-router
2.在src目录下创建一个router目录, 里面创建一个index.js文件 , 这个目录就是router的模块
3.引入第三方的依赖包, 并注册路由:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use( VueRouter ) //使用vue-router这个第三方插件
注意: import这个关键字要放在整个文件的上层
const routes = [
{
path: '/home',
component: Home
}//每一个对象就是一个路由
]
const router = new VueRouter({
routes//路由表 必写的
})
export default router
4.入口文件main.js中引入路由实例 router , 然后在根实例中注册:
import router from './router/index.js'
new Vue({
router,
render: (h) => App
}).$mount('#app')
5.给路由一个路由展示区域
1. 如果是以及路由, 那么我们放在App组件中,用一个 <router-view > </router-view > 的组件表示
6.当页面第一次的打开的时候, 需要做一个重定向, 就是要自动跳转到 /home 这个 路由上:
const routes = [
{ //我们要求这个路由的配置要放在路由表的最上方
path: '/',
redirect: '/home'
}
]
7.业务: 错误路由匹配:
const routes = [
{
path: '/',
redirect: '/home' //重定向
},
{
path: '/error',
component: Error
},
{ //这个就是错误路由匹配, vue规定这个必须放在最下面,它必须将上面的路由全找一遍,找不到才用当前这个
path: '**',
redirect: '/error'
}
] ,
mode:"history"
8.如果你使用 history , 那么我们最好将a标签改成 router-link 这个组件
· router-link 这个组件 身上必须要有一个 to 属性:
· <router-link to='组件的名称'></router-link>
· router-link 这个组件身上加一个 keep-alive属性可以进行浏览器缓存
9.二级路由:
const routes = [
{
path: '/shopcar',
component: Shopcar,
children: [
{
path: 'yyb', // 不写 /
component: Yyb
}
]
}
]
vue-router 进阶 【 分类 -》 列表 -》 详情 】
动态路由 & 路由传参 & 路由接参
1.vue cli3 配置反向代理
在根目录下面新建一个 vue.config.js:
module.exports={
devServer: {
proxy: {
'/index.php': { // /index.php 是一个标记
target: 'http://www.qinqin.net', // 目标源
changeOrigin: true // 修改源
},
}
}
}
2.在列表页面跨域获取数据:
1.先安装:npm i axios -S
<router-link
v-for='e in item.list' :key="e.api_cid" tag='li'
:to="{
name:'index',//需要跳转的详情页面
params:{id:e.api_cid},
query:{
r:'class/cyajaxsub',
cid:e.api_cid,
}}">
<img :src="e.img">
<span>{{e.name}}</span>
</router-link>
<script>
import axios from 'axios'
export default {
data(){
return{
list:[]
}
},
created(){
axios({
url:'/index.php',
params:{
r: "class/category",
type: 1
}
}).then(res=>{this.list=res.data.data.data})
}
}
</script>
3.在详情页面跨域获取数据:
<script>
import axios from 'axios'
export default {
data(){
return{
list:[]
}
},
created(){
axios({
url:'/index.php', //网站详情页的标识符
params:{ //网站详情页的参数
r: this.$route.query.r,//列表页传过来的r
page: 1,
cid: this.$route.query.cid,//列表页传过来的cid
px: 't',
cac_id: ''
}
}).then(res=>{this.list=res.data.data.content}
)
}
}
</script>
编程式导航
· push
· this.$router.push('/home')
· this.$router.push({name,params,query})
· push可以将我们的操作存放到浏览器的历史记录
· replace
· this.$router.replace('/home')
· this.$router.replace({name,params,query})
· replace没有将我们的操作存放到浏览器的历史记录, 效果为返回了二级
· push/replace的参数就是to属性的参数