小兔鲜学习记录:
原笔记地址:http://zhoushugang.gitee.io/erabbit-client-pc-document/guide/03-home.html
1.代码目录
2.路由
在app.vue设置路由出口
<template>
<!-- 一级路由 -->
<router-view></router-view>
</template>
一级路由布局 src/views/Layout.vue
<template>
<nav>顶部通栏</nav>
<header>头部</header>
<main>
<!-- 二级路由 -->
<router-view></router-view>
</main>
<footer>底部</footer>
</template>
<script>
export default {
name: 'xtx-layout'
}
</script>
<style scoped lang='less'></style>
二级路由首页 src/views/home/index.vue
<template>
<div class='xtx-home-page'>
首页
</div>
</template>
<script>
export default {
name: 'xtx-home-page'
}
</script>
<style scoped lang='less'></style>
2者是通过src/router/index.js里的配置联系在一起的
import { createRouter, createWebHashHistory } from 'vue-router'
import TopCategory from '@/views/category'
import SubCategory from '@/views/category/sub'
const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/home/index')
const routes = [
{
path: '/',
component: Layout,
children: [
{ path: '/', component: Home },
{ path: '/category/:id', component: TopCategory },
{ path: '/category/sub/:id', component: SubCategory }]
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
通过routes里面的路由规则,实现了一级路由,二级路由是一级路由的children,所以在一级路由布局里面有二级路由的出口。
3.仓库
import { createStore } from 'vuex'
// 创建vuex仓库并导出
export default createStore({
state: {
// 数据
},
mutations: {
// 改数据函数
},
actions: {
// 请求数据函数
},
modules: {
// 分模块
},
getters: {
// vuex的计算属性
}
})
/src/store/category.js是一个分类的模块
// 存储的分类数据
import { topCategory } from '@/api/constants'
import { findAllCategory } from '@/api/category'
export default {
namespaced: true,
state: () => {
return {
// 如果默认是[]数组,看不见默认的9个分类,等你数据加载完毕才会看到。
// 所以:根据常量数据来生成一个默认的顶级分类数据,不会出现空白(没数据的情况)
list: topCategory.map(item => ({ name: item }))
}
},
// 加载数据成功后需要修改list所以需要mutations函数
mutations: {
setList (state, headCategory) {
state.list = headCategory
},
// 修改当前一级分类下的open数据为true
show (state, item) {
const category = state.list.find(category => category.id === item.id)
category.open = true
},
// 修改当前一级分类下的open数据为false
hide (state, item) {
const category = state.list.find(category => category.id === item.id)
category.open = false
}
},
// 需要向后台加载数据,所以需要actions函数获取数据
actions: {
async getList ({ commit }) {
const { result } = await findAllCategory()
// 给一级分类加上一个控制二级分类显示隐藏的数据open
result.forEach(item => {
item.open = false
})
// 获取数据成功,提交mutations进行数据修改
commit('setList', result)
}
}
}
从里面可以看出
state里面的数据是从@/api/constants这里来的,即下面这个列表
// 顶级分类
export const topCategory = [
'居家',
'美食',
'服饰',
'母婴',
'个护',
'严选',
'数码',
'运动',
'杂货'
]
如果没有请求的话就会使用这一个数组
这个分类实际上是要从后台获取
仓库中的actions去请求数据将结果通过commit提交给mutations,由他去修改数据
使用时:
setup () {
const store = useStore()
const list = computed(() => {
return store.state.category.list
})
const show = (item) => {
store.commit('category/show', item)
}
const hide = (item) => {
store.commit('category/hide', item)
}
return { list, show, hide }
}
使用computed得到仓库里的list,然后在返回list