您的位置:首页 > Web前端 > Vue.js

Vue路由请求数据实现新闻列表及详情页的渲染

2019-03-02 23:15 881 查看

请求数据的接口:
新闻列表接口:http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1

新闻详情接口:http://www.phonegap100.com/appapi.php?a=getPortalArticle&aid=488

[code]main.js中

/*定义路由 */
const routes = [
              { path: '/', component: Home },
              { path: '/Home', component: Home },
              { path: '/News', component: News },
              { path: '/Product', component: Product },//get传值
              { path: '/Content/:aid', component: Content }//动态路由
            
            ]
[code]App.vue
<template>
<div id="app">
<header class="header">
<router-link to="/Home" >首页</router-link>
<router-link to="/News">新闻</router-link>
</header>
<hr>
<router-view></router-view>

</div>
</template>

<script>
export default {
data () {
return {
msg:'hello ,vue!'

}

}
}
</script>

<style lang="scss">
#app{
width:100%;
}
.header{
height: 4.4rem;
line-height: 4.4rem;
background:#000;
color: #fff;
text-align: center;
font-size: 2rem;
a{
color: #fff;
padding: 0 2rem;
}
}

</style>

新闻列表页:

[code]//News.vue页面
<template>
<div>
<ul class="list">
<li v-for="(item,aid) in list" :key="aid">
<router-link :to="'/Content/'+item.aid">{{item.title}}</router-link>
</li>
</ul>
</div>
</template>
<script>

import Bus from '../model/bus'
export default {
data(){
return{
aaa:'m,sh',
list:[]
}
},
methods:{
requestData(){
/* 请求数据
如果用jsonp请求数据的话,后台一定要支持jsonp
*/
var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1'
this.$http.jsonp(api).then(
//  出现this,要注意this的指向问题,es6语法可以避免,或则提前声明that
(response)=>{
// console.log(response)
this.list=response.body.result
},(err)=>{
console.log(err)
})
}
},
mounted(){
//  在dom渲染完成即开始向后台请求数据
this.requestData();
//  通过Bus.on来接收广播的数据
Bus.$on('to-news',function(data){
alert(data)

})
}

}
</script>

<style lang="scss" scoped>
.list{
li{
padding: 1rem;
height: 3.4rem;
line-height: 3.4rem;
border-bottom: 1px solid #fff;
font-size: 1.6rem;
a{
color: #666;
text-decoration: none;

}
}
}
</style>

新闻详情页面:

[code]//Content.vue
<template>
<div id="content">
<h2>{{list.title}}</h2>
<!-- 用v-html解析后台传来的HTML代码 -->
<div  v-html="list.content">

</div>
</div>
</template>
<script>
export default {
data(){
return{
list:[]
}
},
mounted(){
//console.log(this.$route.params)/* 获取动态路由传值 */
var aid=this.$route.params.aid
// console.log(aid)
// 调用requestData()方法请求新闻内容
this.requestData(aid)

},
methods:{
requestData(aid){
// 新闻详情接口
var api='http://www.phonegap100.com/appapi.php?a=getPortalArticle&aid='+aid;
// get请求如果跨域的话,后台php java要允许跨域请求
this.$http.get(api).then((res)=>{
this.list=res.body.result[0]
},(err)=>{
console.log(err)
})
}
}
}
</script>
<style lang="scss" >
#content{
padding: 1rem;
line-height: 2;
img{
max-width: 100%;
}
}
</style>

最后的效果:           

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: