main.js文件:
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
// import VueResourece from 'vue-resource'
// Vue.use(VueResourece)
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// 1.创建组件
import Home from './components/Home'
import News from './components/News'
import Content from './components/Content'
import Pcontent from './components/Pcontent'
import VueResource from 'vue-resource'
Vue.use(VueResource)
// 2.配置路由
const routes = [
{path: '/home', component: Home},
{path: '/news', component: News},
{path: '/content/:aid', component: Content},
{path: '/pcontent', component: Pcontent},
{path: '*', component: Home}
]
// 3、实例化VueRouter
const router = new VueRouter({
routes
})
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: {App},
template: '<App/>'
})
// 5、将<router-view></router-view>放置在app.vue中
Home.vue组件
<template>
<div>
这是Home组件
</div>
</template>
<script>
export default {
name: 'Home'
}
</script>
<style scoped>
</style>
News组件:
<template>
<div>
这是News组件
<!--<ul>-->
<!--<li v-for="(item,key) in list">-->
<!--<router-link :to="'/content/'+key">{{key}}----{{item}}</router-link>-->
<!--</li>-->
<!--</ul>-->
<ul>
<li v-for="(item,key) in list">
<router-link :to="'/pcontent?aid='+item.aid">{{key}}--{{item.title}}</router-link>
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'News',
data () {
return {
msg: '我是一个新闻组件',
list: []
}
},
methods:{
requestData(){
// jsonp请求的话后台api接口也要支持jsonp
var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1'
var that=this
this.$http.jsonp(api).then(function(response){
console.log(response)
that.list=response.body.result
},function(err){
console.log(err)
})
}
},
mounted(){
this.requestData()
}
}
</script>
<style scoped>
</style>
Content.vue:
<template>
<div>
这是content组件
</div>
</template>
<script>
// 动态路由
// 1)配置动态路由
// routes:[
// //动态路径参数,以冒号开头
// {path:'/user/:id',component:User}
// ]
// 2)在对应跳转页面
// this.$route.params获取动态路由的值
export default {
name: 'Content',
mounted(){
console.log(this.$route.params)/*获取动态路由传值*/
}
}
</script>
<style scoped>
</style>
pContent.vue
<template>
<div>
<h1>{{list.title}}</h1>
<p v-html="list.content"></p>
</div>
</template>
<script>
export default {
name: 'Pcontent',
data () {
return {
msg: '我是一个pcontent组件',
list: []
}
},
mounted () {
// console.log(this.$route.query)
// 拿到传进来对应新闻的aid
var aid=this.$route.query.aid
// console.log(aid)
this.requestData(aid)
},
methods:{
requestData(aid){
// get请求如果跨域的话,后台php java里要允许跨域请求
var api='http://www.phonegap100.com/appapi.php?a=getPortalArticle&aid='+aid
this.$http.get(api).then((response)=>{
// console.log(response)
this.list=response.body.result[0]
},(err)=>{
console.log(err)
})
}
}
}
</script>
<style scoped>
</style>