Vue+TS 踩坑记录与方案总结
前言
vue 和 TypeScript 结合的情况下,很多写法和我们平时的写法都不太一样,这里总结我项目开发过程中遇到的问题和问题的解决方案
有些问题可能还没解决,欢迎各位大佬给与提点。
另外,使用本文前可以先看vue 官方文档关于 typescript 的使用讲解
整个 vue 项目的目录结构
大体用 vue-cli 创建的项目,结构基本不变。
这里只写我后来为了解决问题改动的地方
main.ts 中,提示import App from './App.vue'处,找不到 App.vue 这个模块
解决方案:
1、将 shims-vue.d.ts 文件一分为二。
2、在 shims-vue.d.ts 文件同级目录下新建 vue.d.ts(名字不一定叫 vue,如 xxx.d.ts 也可以),然后此文件包含代码如下
// vue.d.ts
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}
3、而原来的 shims-vue.d.ts 代码修改、新增如下:
// shims-vue.d.ts
import Vue from 'vue'
import VueRouter, { Route } from 'vue-router'
import { Store } from 'vuex'
declare module 'vue/types/vue' {
interface Vue {
$router: VueRouter;
$route: Route;
$store: Store;
// 以下是在main.ts中挂载到Vue.prototype上的变量
$api: any;
$mock: any;
$configs: any;
}
}
main.ts 中,往 Vue 的原型 prototype 上挂载全局变量
1、main.ts 配置
// main.ts
import api from "./api/request";
import mock from "./api/mock";
import configs from "./utils/config";
Vue.prototype.\(api = api;
Vue.prototype.\)mock = mock;
Vue.prototype.$configs = configs;
2、shims-vue.d.ts 配置
// shims-vue.d.ts 新增如下
declare module 'vue/types/vue' {
interface Vue {
// ...
// 以下是在main.ts中挂载到Vue.prototype上的变量
$api: any;
$mock: any;
$configs: any;
}
}
全局组件注册
注册
// main.ts
import Page from "@/components/page.vue";
import AllComponent from "@/common/AllComponent.vue";
Vue.component("Page", Page);
Vue.component("all-component", AllComponent);
使用
写法一:
写法二:
SFC 单 vue 文件组件的基本写法和结构
一個简陋的 demo,展示 ts 下的 vue 文件中,对于相关功能的使用,重点关注
结构示例
{ { selfKey1 }}
{ { item }}追加文字
:class="['default-class', selfKey1.length > 10 ? 'one' : 'two']"
/>
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import { Route } from "vue-router";
import AnotherVue from "@/components/AnotherVue.vue";
@Component({
// 组件注册
components: {
AnotherVue
// 'another-vue': AnotherVue
},
// 过滤器
filters: {
filterFn1() {}
},
// 属性传递
props: {
hideHeader: {
type: Boolean,
required: false,
default: false // 默认属性的默认值
}
}
})
export default class Componen