导语:
经常有读者问我,vue的项目目录推荐是怎么样的?我给他们的建议是,尽量把可以复用的组件做成子组件,对经常调用的api封装到一个js文件中,对一些静态资源,把它们放在同一个文件中,便于管理。
1 ,为什么要将这些组件,资源,api封装起来?
便于项目的管理和更新,减少代码量,压缩代码的大小。
2,推荐的项目目录是怎么样的?
3,如何封装api
export function getDiscList() {
const url = '/api/getDiscList'
const data = Object.assign({
}, commonParams, {
platform: 'yqq',
hostUin: 0,
sin: 0,
ein: 29,
sortId: 5,
needNewCode: 0,
categoryId: 10000000,
rnd: Math.random(),
format: 'json'
})
return axios.get(url, {
params: data
}).then((res) => {
// 这里返回一个Promise的resolve方法,把需要的参数传递出去
return Promise.resolve(res.data)
})
}
然后在需要的地方导入封装的api :import {getDiscList} from ‘…/…/api/index.js’就可以了。
这样你以后想要改这个接口,不用到每个业务组件里面修改,只需要在这个api上面统一修改就可以了,方便省力。
4,如何封装通用子组件
你的项目中是否有很多的input输入框,加载悬浮框这些基础通用组件,那么你就可以把他写成一个通用子组件,就可以做到只写一次,复用多次,大大提高写代码的速度,同时也提高了项目的质量。
<template>
<div class="loading">
<img width="24" height="24" src="./loading.gif">
<p class="desc">{
{title}}</p>
</div>
</template>
<script type="text/ecmascript-6">
export default {
props: {
title: {
type: String,
default: '正在载入...'
}
}
}
</script>
<style scoped lang="stylus" rel="stylesheet/stylus">
@import "~common/stylus/variable"
.loading
width: 100%
text-align: center
.desc
line-height: 20px
font-size: $font-size-small
color: $color-text-l
</style>
然后你就可以像调用子组件一样,复用这个加载框。
补充:
微信搜索【web小馆】,回复全栈博客项目,即可获取项目源码和后续的实战文章教程。每天用最简单朴实的语言,潜移默化的提升你的计算机基础知识和前端技术。小米粥,一个专注的web全栈工程师,我们下期再见!
转载:https://blog.csdn.net/gitchatxiaomi/article/details/108809764
查看评论