本模块主要讲解Vue实战中遇到的一些技术点,通过一个课程管理项目的实操来讲解在实战中如何使用Vue进行开发。
Vue项目中使用TypeScript
在vue项目中使用ts有两种情况,一、在新项目中使用TypeScript;二、在已有Vue项目中使用TypeScript。
在新项目中使用TypeScript
使用@vue/cli工具创建是选择使用ts即可。创建完的项目中会有两个ts文件。
其中shims-ts.d.ts文件是jsx语法的类型补充
/**
* Jsx 类型声明补充
*/
import Vue, {
VNode } from 'vue'
declare global {
namespace JSX {
// tslint:disable no-empty-interface
interface Element extends VNode {
}
// tslint:disable no-empty-interface
interface ElementClass extends Vue {
}
interface IntrinsicElements {
[elem: string]: any
}
}
}
shims-vue.d.ts则是.vue文件的类型声明
/**
* import xx from 'xxx.vue'
* ts 无法识别.vue文件
* 通过这个声明.vue模块都是Vue
*/
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}
在已有项目中使用TypeScript
只要使用@vue/cli来安装ts插件即可。
vue add @vue/typescript
TypeScript方式定义vue组件
TypeScript定义vue组件有两种方式:
-
使用Vue.component或Vue.extend定义组件,即OptionApi的方式定义组件。
import Vue from 'vue' export default Vue.extend({ name: 'App' })
-
使用vue-class-component装饰器。装饰器语法尚未定案,并不稳定,不推荐在生成中使用。
import Vue from 'vue' import Component from 'vue-class-component' @Component({ name: 'App' // 选项参数 }) export default class App extends Vue { // 初始数据可以直接声明为实例的 property message: string = 'Hello!' // 组件方法也可以直接声明为实例的方法 onClick (): void { window.alert(this.message) } }
在Vue项目中使用elementUI
要在Vue项目中使用elementUI,只需要安装之后,然后引入即可。
elementUI的引入有两种情况,完整引入和按需引入。
完整引入
引入整个Element。在main.ts中添加以下代码
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
按需引入
需要借助 babel-plugin-component插件。安装插件之后,修改babel配置如下:
{
"presets": [["es2015", {
"modules": false }]],
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
在main.ts中注册要使用的组件
import Vue from 'vue';
import {
Button, Select } from 'element-ui';
import App from './App.vue';
Vue.component(Button.name, Button)