详细的将代码复制到html文件中 记得更改js文件地址
ul{
list-style: none;
margin: 0;
padding: 0;
}
li{
line-height: 30px;
}
<div id="app">
<!--
keep-alive
可以缓存组件包含动态组件和路由组件
缓存的组件再次进入时不会触发生命周期也就是说组件不会重新渲染
而且keep-alive会记录保留下来的页面的所有信息包括滚动高度
-->
<keep-alive>
<router-view :key="$route.fullPath"></router-view>
</keep-alive>
</div>
<script src="../../js/vue.js"></script>
<script src="../../js/vue-router.js"></script>
<script src="../../js/axios.min.js"></script>
<script>
const firstPage= {
template: `
<div id="firstPage">
<ul>
<router-link :to="{
path: '/secondPage',
query: {
id: item.id
}
}" tag="li" v-for="item in topics" :key="item.id">{{item.title}}</router-link>
</ul>
</div>
`,
data() {
return {
topics: []
}
},
created() {
this.getTopics()
},
methods: {
getTopics() {
axios.get('https://cnodejs.org/api/v1/topics').then(res => {
this.topics = res.data.data
})
}
}
}
const secondPage= {
template: `
<div id="secondPage">
<router-link to="/">返回</router-link>
<div v-html="detail.content"></div>
</div>
`,
data() {
return {
detail: {}
}
},
created() {
this.getTopicDetail()
},
methods: {
getTopicDetail() {
axios.get(`https://cnodejs.org/api/v1/topic/${this.$route.query.id}`).then(res => {
this.detail = res.data.data
})
}
}
}
const routes = [
{
path: '/',
component: firstPage
},
{
path: '/secondPage',
component: secondPage
}
]
let router = new VueRouter({
routes,
scrollBehavior (to, from, savedPosition) {
// console.log(to)
// console.log(from)
// console.log(savedPosition) // (通过浏览器的 前进/后退 按钮触发)
return {x: 0, y:0}
}
})
var vm = new Vue({
el:'#app',
router,
data:{},
methods:{}
});