引子
差不多首页显示已经完成,那么现在需要为首页的那么多分类设置点击事件了。
1.设置点击样式
布局页优化,在layout/default.vue中添加如下代码:
.header-menu{
margin-left: 30px;
}
下面则主要操作pages/index.vue页面了。 为目录设置点击事件:
<ul class="clear-fix" >
<li :class="index!==0?'float-left':'float-left recommend-menu-active'" v-for="(item, index) in categories" :key="index"
@click="onCategoryItemClick(item)">
{{item.favorites_title}}
</li>
</ul>
并为点击事件设置方法:
methods:{
onCategoryItemClick(item){
this.currentCategory = item.favorites_title.split("").join("<em>/</em>");
},
},
2.加载数据
在介绍加载数据之前,需要先了解一下什么是跨域请求。 文章:什么是跨域?如何解决跨域问题?介绍:
什么是跨域? 浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域 域名: 主域名不同 http://www.baidu.com/index.html -->http://www.sina.com/test.js 子域名不同 http://www.666.baidu.com/index.html -->http://www.555.baidu.com/test.js 域名和域名ip http://www.baidu.com/index.html -->http://180.149.132.47/test.js 端口: http://www.baidu.com:8080/index.html–> http://www.baidu.com:8081/test.js 协议: http://www.baidu.com:8080/index.html–> https://www.baidu.com:8080/test.js 备注: 1、端口和协议的不同,只能通过后台来解决 2、localhost和127.0.0.1虽然都指向本机,但也属于跨域
好了,现在我们修改代码,当点击对应栏目后,页面数据发生变动,主要是修改方法,如下:
methods:{
onCategoryItemClick(item){
this.currentCategory = item.favorites_title.split("").join("<em>/</em>");
// 加载内容
this.loadContentByCategory(item.favorites_id);
},
loadContentByCategory(favoriteId){
api.getRecommendContent(favoriteId).then(result =>{
// console.log(result)
this.content = result.data.tbk_dg_optimus_material_response.result_list.map_data;
})
}
},
很神奇的是,我这里并没有出现跨域请求的问题。以下是大锯视频中的跨域请求问题: 为了避免下次出现跨域请求出错,我们还是跟着大锯去解决跨域请求问题。首先看看官网是如何解决的:https://zh.nuxtjs.org/docs/2.x/features/data-fetching/#async-data.
那么我们接下来就是安装代理js:
cnpm install @nuxtjs/proxy --save
然后去nuxt.config.js文件中进行相关的配置:
modules: [
'@nuxtjs/proxy',
],
axios:{
proxy:true,
prefix:'/union/',
credential:true,
},
proxy:{
'/union/':{
target:'https://api.sunofbeach.net/shop/',
pathRewrite:{
changeOrigin:true,
'^/union/':''
}
}
},
接下来就需要书写相关api请求代理链接的方法了,在utils/api.js增加代理方法:
// 获取首页菜单类内容的代理方法
getRecommendContentByProxy(categoryId){
return request.requestGet('/union/' + "recommend/" + categoryId);
},
然后继续修改pages/default.vue中的方法:
methods:{
onCategoryItemClick(item){
this.currentCategory = item.favorites_title.split("").join("<em>/</em>");
// 加载内容
this.loadContentByCategory(item.favorites_id);
},
loadContentByCategory(favoriteId){
api.getRecommendContentByProxy(favoriteId).then(result =>{
if(result.code === 10000){
this.content.length = 0; // 先清空数据
this.content = result.data.tbk_dg_optimus_material_response.result_list.map_data;
}
})
}
},
效果如下:
好了,可能数据刷新有点慢,后面继续优化吧。