这是第三篇关于美食杰这个项目的介绍和实现效果啦!关于前两篇可以我的主页中去观看。如果又不懂得及时通知我。
下面说一下这个效果吧!
先上图,这样看得懂!
以上都是我们要实现的效果!
下面开始讲解一下我们要实现效果的过程啦!
第一步:我们首先要将后端数据获取到,这个就是 import {getClassify, getProperty, getMenus} from '@/service/api';
第二步:调用获取到的数据data将其进行解构,保存到我们在新建的空数组classify:[ ]中。
getClassify().then(({data})=>{
// console.log(data);
this.classify = data;
})
}
});
第三步:渲染数据,就是将在classify数组中的数据在页面中渲染。首先是通过v-for循环解构后里面的数据,然后就是绑定key值。通过动态绑定label和name属性实现路由的监听。
<el-tabs v-model="classifyName" type="border-card" >
<el-tab-pane
v-for="item in classify"
:key="item.parent_type"
:label="item.parent_name"
:name="item.parent_type">
<div class="recipe-link">
<router-link :to="{query:{...$router.query,classify:option.type}}"
v-for="option in item.list"
:key="option.type"
:class="{active:classifyType === option.type}">
{{option.name}}
</router-link>
</div>
</el-tab-pane>
</el-tabs>
第四步:就是实现路由的深度监听来试试各个组件的跳转,但是刚开始加载时会有延迟效果,这时我们需要用到immediate:true
watch: {
$route: {
handler(){
const {classify} = this.$route.query;//lu
if (classify) {
this.classifyType = classify;//存好的二级在这里 1-1
this.classifyName =classify[0];//这样就变为一级 1
}
this.ThisgetMenus()//这里需要改
},
immediate:true
}
},
这就实现我们的路由跳转和二级切换路由。
接下来就是我们的属性之间的分类
这个跟上面的效果差不多都是先将后端数据获取到,
第二步:调用获取到的数据data将其进行解构,保存到我们在新建的空数组properties:[ ],存储属性中的所有数据中。
getProperty().then(({data})=>{
// console.log(data);
this.properties = data;
const {query} = this.$route; // {craft:'1-1',flavor: '2-1',hard: '3-2' }
//传递空对象,来保存每次的参数值
this.propertyType = this.properties.reduce((o, item) => {
//item.title 工艺,难度,口味,人数
o[item.title] = query[item.title] ? query[item.title] : '';
return o;
},{});
// console.log(this.propertyType);
})
第三步:渲染数据,就是将在properties数组中的数据在页面中渲染。首先是通过v-for循环解构后里面的数据,然后就是绑定key值。通过动态绑定label和name属性实现路由的监听。
<el-collapse v-model="propertiesActivName">
<el-collapse-item
v-for="item in properties"
:key="item.parent_type"
:title="item.parent_name"
:name="item.parent_type">
<div class="filter-tags">
<el-tag type="info"
v-for="option in item.list"
:key="option.type"
@click="selectedTag(option)"
:class="{'tag-selected': propertyType[option.title] === option.type}" >
{{option.name}}
</el-tag>
</div>
</el-collapse-item>
</el-collapse>
第四步:这里判断是否点击,如果点击过:取消,否则,选中
selectedTag(option){
let query = {...this.$route.query};
//判断是否点击,如果点击过:取消,否则,选中
if (this.propertyType[option.title] === option.type) {
this.propertyType[option.title]="";
delete query[option.title];
}else{
this.propertyType[option.title]=option.type;
query[option.title]=option.type;
}
// 地址栏记录选中的属性
this.$router.push({
query
})
}
这样就可以实现这个,零碎的组件了!
但是,关于缓存部分,添加immediate,在初始化时也会执行watch回调函数,组件加载立即执行。
要使用immediate需要添加handler属性
在组件加载完成时,立即执行watch回调函数,即在created前执行。
后面的执行顺序同无immediate时。
这个是需要注意的地方。