前言:
为什么要编写这篇文章?一是对自己技术的磨练,二是给大家分享如何使用vue+typescript开发项目。
大佬就不要喷我的代码了。主要面向技术一般般的同学,没有写过typescript。当然我技术也是一般般。
正文:
我假设你已经熟练应用过vue全家桶(vue+router+vuex+axios[‘黑人问号脸?’])
另外先泡一杯咖啡!
在这里我也不教你如何配置环境了直接开始正题,let's go!
第一阶段配置项目并启动
当前开发版本:
vue create projectName //projectName 是指你的项目名称
复制代码
这里可以选择默认模板和和自己配置。
这里我选择的是第二个,然后又让你选择……
扫描二维码关注公众号,回复: 3594597 查看本文章
这里的选择可以按数字键选择的
- Babel =====> 1
- TyepScript ====> 2
以次类推,所以你懂我意思吧
这里选择我们需要的几个东东,然后愉快的回车把,喝一会咖啡等待项目安装完成。
安装完成之后我们先看下文件目录
细心的同学肯定发现了少了 build 和config 文件夹。那么如果我配置webpack 怎么办?新建一个 vue.config.js 不明白的同学可以点击这里
那么开始安装我们需要的一些依赖!
npm i vant -S // ui框架
npm i babel-plugin-import -D // 使用 babel-plugin-import
npm install --save-dev sass-loader // sass
npm install --save-dev node-sass // sass-loader依赖于node-sass
npm install --save vuex-class // 更方便使用vuex
npm i axios -S // axios
复制代码
最后几步
在配置文件babel.config.js 中加上:
"plugins": [
["import", {
"libraryName": "vant",
"libraryDirectory": "es",
"style": true
}]
]
复制代码
删除已经无用的about.vue
在components中新建Header.vue 并写入代码
<template>
<div class="header">
<van-nav-bar
title="首页"
/>
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { NavBar } from 'vant';
@Component({
components: {
[NavBar.name]: NavBar,
},
})
export default class Header extends Vue {
}
</script>
<style scoped>
</style>
复制代码
App.vue的标签后面写入
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { NavBar } from 'vant';
import Header from '@/components/Header.vue';
@Component({
components: {
Header
},
})
export default class App extends Vue {
}
</script>
复制代码
删除Home.vue的代码,写入
<template>
<div class="home">
<p>第一个vue+typescript应用</p>
</div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
export default class Home extends Vue {}
</script>
复制代码
应该是编辑器的bug,有些代码会提示bug,不过我们视终端和浏览器控制台的报错才是真正的报错!
在控制台输入npm run serve
第二阶段 封装axios 和 使用vuex
在scr目录下新建utils和store两个文件夹
utils新建立request.ts
import * as axios from 'axios';
import store from '@/store';
import { Toast } from 'vant';
import { AxiosResponse, AxiosRequestConfig } from 'axios';
const baseURL = 'https://api.douban.com/v2/movie/';
const service = axios.default.create({
baseURL,
timeout: 0,
maxContentLength: 4000,
});
service.interceptors.request.use((config: AxiosRequestConfig) => {
return config;
}, (error: any) => {
Promise.reject(error);
});
service.interceptors.response.use(
(response: AxiosResponse) => {
if (response.data.start !== 0) {
Toast.fail('请求错误!');
} else {
return response.data;
}
},
(error: any) => {
return Promise.reject(error);
});
export default service;
复制代码
新建ajax.ts
export interface AjaxResponse {
code: number;
data: any;
message: string;
}
复制代码
axios 简单封装完成。
vue.config 跨域设置 vue官网webpack配置
module.exports = {
configureWebpack: config => {
},
devServer: {
proxy: {
'/api': {
target: 'http://api.douban.com/v2',
changeOrigin: true,
ws: true,
pathRewrite: { //一定要加上这个!!!!不然不能跨域,亲身体验!
'^/api': ''
}
}
}
}
}
复制代码
store 接口类型为了方便复用全部写在store/interface.ts, 每个view组件对应一个文件夹。
store/home/index.ts
import { State } from '@/store/interface';
import { Commit } from 'vuex';
import { getMovieList } from '@/api/home';
const state: State = {
movieList: [],
};
const getters = {
// tslint:disable-next-line:no-shadowed-variable
movieList: (state: State) => state.movieList,
};
const mutations = {
};
const actions = {
async movieList(context: { commit: Commit }, cate: string) {
const res: any = await getMovieList(cate)
.then( (response: any ) => response)
// tslint:disable-next-line:no-console
.catch((e: string) => console.error(e));
return res;
},
};
export default {
state,
getters,
mutations,
actions,
};
复制代码
http请求代码则放在src/api下,同样的每一个view组件对应一个文件。
home.ts
import request from '@/utils/request';
// tslint:disable-next-line:only-arrow-functions
export const getMovieList = function(cate: string) {
return request({
url: '/api/movie/' + cate ,
method: 'GET',
});
};
复制代码
第三阶段 首页编写
如何在vuex中使用 点击此处
home.vue
<template>
<div class="home">
<van-tabs v-model="active">
<van-tab title="正在热映">
<div id="listMovieBox">
<div class="item" v-for="(item, index) in movieListData" :key = 'index'>
<a >
<div class="movie-cover">
<img :src="item.images.small" width="88" height="110">
</div>
<div class="movie-des">
<p class="title">{{item.title}}</p>
<p class="genres"><span>类别:</span><span v-if="item.genres.length === 0">未知</span><span v-else-if="item.genres">{{item.genres}}</span></p>
<p class="cast">
主演:<span v-for="items in item.casts" style="margin-right: 4px;">{{ items.name}}</span>
</p>
<p class="director">导演:<span v-if="item.casts[1]">{{ item.casts[1].name }}</span></p>
<p class="ratings">{{item.rating.average}} <span>分</span></p>
</div>
</a>
</div>
</div>
</van-tab>
<van-tab title="即将上映">
</van-tab>
<van-tab title="Top250">
</van-tab>
</van-tabs>
</div>
</template>
<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import {Action, Mutation, State} from 'vuex-class';
import { Tab, Tabs } from 'vant';
@Component({
components: {
[Tab.name]: Tab,
[Tabs.name]: Tabs,
},
})
export default class Home extends Vue {
private cate = 'in_theaters';
private active = 0;
private movieListData = [];
@Action private movieList!: (cate: string) => any;
private created() {
this.movieList( this.cate ).then( (res: any) => {
this.movieListData = res.subjects;
});
}
}
</script>
<style lang="sass">
#listMovieBox
padding: 0 16px
.item
padding: 10px 0
border-bottom: 1px solid #eee
a
position: relative
display: flex
.movie-cover
width: 88px
flex: 0
height: 110px
color: #000
.movie-des
flex: 1
padding-left: 10px
vertical-align: top
.ratings
position: absolute
font-size: 20px
font-weight: bold
font-family: "Microsoft New Tai Lue"
color: #FFB400
right: 0px
top: 16px
span
font-size: 14px
.title
line-height: 1.5rem
padding-top: 4px
font-size: 16px
.genres
font-size: 12px
color: #666
line-height: 24px
.cast
font-size: 12px
width: 200px
overflow: hidden
white-space: nowrap
text-overflow: ellipsis
color: #666
line-height: 24px
.director
font-size: 14px
color: #999
line-height: 26px
</style>
复制代码
最后说几句
应该是8月份的时候我开始使用vue+typescript写项目。
也是查了不少的资料看了一些文章,当然我这里也是看了大佬们的文章和代码加上一点点自己的理解写的文章。
这里列举一下我参考的文章和资料 文章:
代码: