今天主要实现菜品详情页的数据渲染和评论
评论可以提交
1.在data里面定义一个存储从后端接收的数据
data(){
return {
menuInfo:[]//接收菜谱的详细信息
}
},
2.watch监听,如果有参数就将从后端获取的数据赋值给data里面定义的数组,如果没有参数就警告用户重新进入页面,把后端中的方法用import引入。
watch:{
$route:{
handler(){
//获取参数
let {menuId} = this.$route.query;
if(menuId){//发布请求
menuInfo({menuId}).then(({data})=>{
//将请求到的数据赋值给data里面定义的数组
this.menuInfo=data.info;
console.log(this.menuInfo);
})
}else{
// 如果没有参数,就警示用户
this.$message({
showClose:true,
message:'请重新进入',
type:'warning'
})
}
},
// 初始化监听
immediate:true
}
}
3.在标签中将数据传给子组件
<div class="menu-detail">
<!-- 向子组件传参 -->
<detail-header :info="menuInfo"></detail-header>
<detail-content :info="menuInfo"></detail-content>
<Comment :info="menuInfo"></Comment>
</div>
4.在子组件中用props接收数据
props:{
info: {
type: Object,
default: () => ({})
}
},
5.渲染数据(笔者在此不做展示)
6.“收藏”和“已收藏”切换。
<a
href="javascript:;"
class="collection-at"
:class="{'no-collection-at':info.isCollection}"
@click="collectHandler"
>
{{info.isCollection?'已收藏':'收藏'}}
</a>
isCollection是他的状态,初始为false,在info数据里面
写入点击事件
methods:{
async collectHandler(){
const {data} = await toggleCollection({menuId:this.info.menuId})
console.log(data);
this.info.isCollection = data.isCollection;
}
}
7.如果用户进的是自己发布的作品,就隐藏收藏按钮
computed: {
isOnwer(){
return this.info.userInfo.userId === this.$store.state.userInfo.userId
}
},
在收藏的父标签上绑定isOnwer
<div class="detail-collection" v-if="!isOnwer">
<a
href="javascript:;"
class="collection-at"
:class="{'no-collection-at':info.isCollection}"
@click="collectHandler"
>
{{info.isCollection?'已收藏':'收藏'}}
</a>
</div>
8.评论
在data中定义存储数据的数组
data(){
return {
comments:[],//接收数据
commentText:""//评论内容
}
},
9.接收后端的数据
computed: {
// 后端数据
userInfo(){
return this.$store.state.userInfo
},
// 登录状态
isLogin(){
return this.$store.getters.isLogin
}
},
10.从后端获取评论的数据
async mounted(){
// 获取评论的信息
let {menuId} = this.$route.query;
if(menuId){
let data=await getComments({menuId:menuId})
this.comments = data.data.comments
}
}
11.点击事件
methods:{
// 提交评论方法
async send(){
//通过后端方法传参
let data = await postComment({menuId:this.info.menuId,commentText:this.commentText});
// console.log(data);
//将提交的内容添加到data中定义的数组
this.comments.unshift(data.data.comments);
//当用户提交后,清空文本框里的内容
this.commentText="";
}
},
欧了。冲冲冲!!!