main.js
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
router.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home' //为什么要加@
import Detail from '@/components/Detail'
import VueResource from 'vue-resource'
Vue.use(VueResource)
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Hello',
component: Home
},
{
path: '/detail/:id',
name: 'detail',
component: Detail
},
// { path: '*', redirect: '/' }
]
})
跳转
<!-- Home.vue -->
<template>
<div class="container">
<!-- 由于html不区分大小写,所以js中驼峰命名方式在html中要改成用短横线连接的形式 -->
<home-header></home-header>
<div class="content">
<ul class="cont_ul">
<list v-for="item in items" :price="item.price" :title="item.title" :img="item.img" >
</list>
</ul>
</div>
</div>
</template>
<script>
// 导入要用到的子组件
import HomeHeader from './HomeHeader'
import List from './List'
export default {
data () {
return {
items: [ ]
}
},
// 在components字段中,包含导入的子组件
components: {
HomeHeader,
List
},
// 在组件创建完成时,执行的钩子函数
created (){
// 在main.js里导入并使用vue-resource之后,就可以通过this.$http来使用vue-resource了,这里我们用到了get方法
this.$http.get('/api/books').then((data) => {
// 由于请求成功返回的是Promise对象,我们要从data.body.data拿到books数组
// this.items = data.body.data;
})
}
}
</script>
this. $router. push({ name: 'regist'});
go(){history. go(- 1);}
传递参数
<!-- List.vue -->
<template>
<li class="sec_li">
<router-link :to="{ name: 'detail', params: { id: price }}" class="lp_li_a">
<div class="lp_li_imgWrap">
![]( img )
</div>
<p class="lp_li_name">{{ title }}</p>
<p class="lp_li_price">¥{{ price }}元</p>
</router-link>
</li>
</template>
<script>
export default {
props: ['price', 'title', 'img']
}
</script>
接受参数
<!-- Detail.vue -->
<template>
<div class="detail">
<detail-header></detail-header>
<h1>{{this.$route.params.id}}</h1>
</div>
</template>
<script>
import DetailHeader from './DetailHeader'
export default {
components: {
DetailHeader
}
}
</script>
返回
<!-- DetailHeader.vue -->
<template>
<header class="header">
<div class="header_inner flexWrap">
<div
id="header_btn_nav"
class="header_btn header_btn_back"
v-on:click="goBack"
>返回</div>
<div class="header_cont flex">详情</div>
<div class="header_btn header_btn_cart"></div>
</div>
</header>
</template>
<script>
export default {
methods: {
goBack(){
window.history.back();
}
}
}
</script>