产品详情页面开发
本节完成鲁嗑食品网站的最后一个功能,即产品详情页。产品详情页面有 3 个知识点需要重点掌握。
(1)产品详情页面和首页、全部产品页面不同,它不属于嵌套路由。 (2)使用链式路由跳转进入详情页面。 (3)产品详情页面获取产品页面传递过来的参数。
新建产品详情页面,如图 11-15 所示。

Figure 1. 图11-15 新建产品详情页面
创建路由匹配规则,代码如下。
import Vue from 'vue';
import Router from 'vue-router';
import index from '../views/index';
import home from '../components/home.vue';
import alllist from '../views/productList';
// 1. 引入产品详情组件
import detail from './views/product';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'index',
component: index,
children: [
{
path: '/',
name: 'home',
component: home
},
{
path: '/alllist',
name: 'alllist',
component: alllist
}
]
},
// 2. 创建产品详情匹配规则
{
path: '/detail',
name: 'detail',
component: detail
}
]
});
单击产品图片,进入详情页面,为图片绑定单击事件,代码如下。
此时单击产品图片可以跳转到详情页面,只需要调用产品详情接口,获取真实数据即可。 产品详情接口地址为 http://api.mm2018.com:8095/api/goods/productDet?productId=150642571432851 。
请求方式:get请求。
获取产品页面传递的 productId,代码如下。
<div class="index_hot_main">
<ul>
<li v-for="(item, i) in allList" :key="i">
<img :src="item.productImageUrl" @click="toLink(item.productId)" />
<p>
{{ item.productName }}<br />{{ item.salePrice }}元
</p>
</li>
</ul>
</div>
// 事件代码
methods: {
toLink(pid) {
this.$router.push({
path: `detail?productid=${pid}`
});
}
}
此时单击产品图片可以跳转到详情页面,只需要调用产品详情接口,获取真实数据即可。
请求方式:get请求。
获取产品页面传递的 productId,代码如下。
<template>
<div>
<h1>产品详情</h1>
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {},
created() {
// 获取传递过来的 productid
console.log(this.$route.query.productid);
var pid = this.$route.query.productid;
}
};
</script>
调用接口,获取真实数据,代码如下。
<template>
<div>
<h1>{{ detailData.productName }}</h1>
<div v-html="detailData.detail"></div>
</div>
</template>
<script>
export default {
data() {
return {
detailData: {}
};
},
methods: {
// 调用接口获取数据
getdata(id) {
this.$axios({
methods: 'get',
url: `http://api.mm2018.com:8095/api/goods/productDet?productId=${id}`
}).then(res => {
// console.log(res.data)
this.detailData = res.data;
});
}
},
created() {
// 获取传递过来的 productid
var pid = this.$route.query.productid;
// 生命周期函数调用方法
this.getdata(pid);
}
};
</script>
项目总结:通过鲁嗑食品有限公司企业网站案例,主要练习 vue-cli 创建项目、element-ui 的使用、各种 Vue 指令的使用、路由以及嵌套路由的使用等,最终达到使用 Vue 制作前端企业网站的目标。