<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<!--
在组件中获取url里的query参数
this.$route.query.tab
拿个这个参数请求数据
axios.get(url, {
params: {
tab
}
})
请求到的数据设置给组件的topics
this.topics = res.data.data
设置好对应的路由
const routes = [
{
path: '/',
component: Index
}
]
把路由配置加到Router
const router = new VueRouter({
routes
})
把router加入到new Vue
new Vue({
el: "#app",
router
})
所有链接应该用 router-link表示。对应跳转的地址用 to表示
-->
<div id="app">
<nav>
<router-link to="/?tab=all">全部</router-link>
<router-link to="/?tab=good">精华</router-link>
<router-link to="/?tab=share">分享</router-link>
<router-link to="/?tab=ask">问答</router-link>
<router-link to="/?tab=job">招聘</router-link>
</nav>
<keep-alive>
<router-view :key="$route.fullPath"></router-view>
</keep-alive>
</div>
<script src="./vue.js"></script>
<script src="./vue-router.js"></script>
<script src="./axios.js"></script>
<script>
/*
查询参数 query
url?key=value&key2=value2
通过该方式传参,我们可以在前端通过$route.query.key获取到对应的参数
this.$route.query.key
// 因为这几个url只是query参数发生了改变,对应的组件没有任何改变。所以组件的create只会执行一次,那么我们可以给router-view上添加key为唯一值
给router-view添加keep-alive 可以解决url切换过程中重新请求的问题
*/
const Loading = {
template: `
<div>正在加载中</div>
`
}
Vue.component('Loading', Loading)
const Index = {
template: `
<div>
<Loading v-if="show" />
<p v-for="topic in topics">{{topic.title}}</p>
</div>
`,
data () {
return {
topics: [],
show: true
}
},
created () {
// console.log(this.$route.query.tab)
// 获取到对应的类别 ?tab=xxx
console.log(this.$route)
// 从url中获取参数
const tab = this.$route.query.tab
this.show = true
// 发起请求
axios.get('https://cnodejs.org/api/v1/topics', {
params: {
// tab: tab
tab
}
}).then(res => {
console.log(res.data)
this.topics = res.data.data
this.show = false
})
}
}
const routes = [
{
path: '/',
component: Index
}
]
const router = new VueRouter({
routes
})
const app = new Vue({
el: '#app',
router
})
</script>
</body>
</html>
vue-router路由_根据url的不同,请求不同的列表数据
最新推荐文章于 2024-05-08 19:14:55 发布