vue 和 TypeScript 結合的狀況下,不少寫法和咱們平時的寫法都不太同樣,這裏總結我項目開發過程當中遇到的問題和問題的解決方案 有些問題可能還沒解決,歡迎各位大佬給與提點。 另外,使用本文前能夠先看vue 官方文檔關於 typescript 的使用講解javascript
這裏只寫我後來爲了解決問題改動的地方css
解決方案: 一、將 shims-vue.d.ts 文件一分爲二。 二、在 shims-vue.d.ts 文件同級目錄下新建 vue.d.ts(名字不必定叫 vue,如 xxx.d.ts 也能夠),而後此文件包含代碼以下html
// vue.d.ts
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}複製代碼
三、而原來的 shims-vue.d.ts 代碼修改、新增以下:vue
// 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<any>;
// 如下是在main.ts中掛載到Vue.prototype上的變量
$api: any;
$mock: any;
$configs: any;
}
}複製代碼
一、main.ts 配置java
// 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;複製代碼
二、shims-vue.d.ts 配置webpack
// shims-vue.d.ts 新增以下
declare module 'vue/types/vue' {
interface Vue {
// ...
// 如下是在main.ts中掛載到Vue.prototype上的變量
$api: any;
$mock: any;
$configs: any;
}
}複製代碼
註冊ios
// main.ts
import Page from "@/components/page.vue";
import AllComponent from "@/common/AllComponent.vue";
Vue.component("Page", Page);
Vue.component("all-component", AllComponent);複製代碼
使用git
寫法一:
<Page />
寫法二:
<all-component />複製代碼
一個簡陋的 demo,展現 ts 下的 vue 文件中,對於相關功能的使用,重點關注<Script>
裏的代碼github
<template>
<!-- 結構示例,指令基礎用法同vue --> <div class="minos-system-setting" v-if="hideHeader"> <h3>結構示例</h3> <span>{{ selfKey1 }}</span> <ul> <li :key="item" v-for="item in fatherKey">{{ item }}</li> </ul> <button @click="addText">追加文字</button> <AnotherVue :class="['default-class', selfKey1.length > 10 ? 'one' : 'two']" /> </div> </template> <script lang="ts"> 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 ComponentName extends Vue { @Prop({ type: Boolean, required: false, default: false // 默認屬性的默認值 }) private hideHeader!: boolean | undefined; @Prop() private fatherKey: string[]; // 其餘沒有默認值的傳值 selfKey1: string = "本身的一個變量"; // 生命週期 created() {} mounted() {} // 計算屬性 get computedKey() { return this.selfKey1.length; } // 監聽器 @Watch("computedKey") getcomputedKey(newVal) { console.log(newVal); } // 導航守衛函數 private beforeRouteEnter(to: Route, from: Route, next: () => void): void { console.log("beforeRouteEnter", to, from, next); next(); } // 方法 addText() { this.selfKey1 += ",追加文字!"; } } </script> <style lang="scss" scoped> @import "@/assets/styles/demo.scss"; </style>複製代碼
// 計算屬性
get computedKey() {
return this.selfKey1.length
}複製代碼
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
@Watch('boxHeight')
getboxHeight(val) { // get+上邊括號裏的名字
// xxx
}複製代碼
子組件監遵從父組件傳過來的值 一、父組件用屬性傳值【前提是父組件引入子組件、註冊並調用了】web
<ziZuJian :oneKey="oneKeyObj" />複製代碼
二、子組件要使用的工具引入工做
import { Component, Vue, Prop, Watch } from "vue-property-decorator";複製代碼
三、子組件 Prop 接受
export default class ZiZuJian extends Vue {
@Prop() private oneKey: object
}複製代碼
四、子組件 Watch 監聽
@Watch('oneKey')
getoneKey(newVal,oldVal) {
// 監聽成功後要作
log(newVal)
this.myfunction(newVal)
}複製代碼
五、父組件(內部)改動值,會被子組件監聽
export default class FuZuJian extends Vue {
oneKeyObj = {}
...
mounted(){
$.ajax().then(()=>{
// 適時狀況下改動props傳遞的值,就會被子組件監聽到改變
oneKeyObj = {
name : '測試'
}
oneKeyObj.age = 18
})
}
}複製代碼
主要思路是計算屬性獲取 state 裏的數據,watch 再監聽計算屬性
import { Component, Vue, Prop, Watch } from 'vue-property-decorator' // 引入Watch
get stateSomeKey() { // 計算屬性
// 監聽state下的stateSomeKey對象中的keyName屬性,return返回該值
return this['$store'].state.stateSomeKey.keyName
}
@Watch('stateSomeKey') // 與上邊計算屬性同名
getstateSomeKey(val) { // get+上邊括號裏的名字
// 監聽到變化後,執行對應的內容
this.myFunction()
...
}複製代碼
其中,第七行,監聽器那裏也能夠這麼寫
@Watch('stateSomeKey') // 與上邊計算屬性同名
watchMenuState(val) { // 這裏能夠這麼寫:或用watch+上邊括號裏的名字也能夠(雖然不太肯定爲何,只是代碼這麼寫成功了)
// 下同
// ...
}複製代碼
定義:(在@Component 裏邊,寫 filters,注意 s 單詞)
<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";
@Component({
filters: {
filterValue(value) {
return Number(value).toLocaleString();
}
// otherFilterFn(value) { 其餘filter示例
// return ...
// }
},
components: {}
})
export default class Container extends Vue {
// ...
}
</script>複製代碼
使用:同以前,正常使用:
<span v-if="showSpan">{{showValue | filterValue}}</span>複製代碼
// 待補充複製代碼
一、shims-vue.d.ts 的設置
// shims-vue.d.ts
import Vue from 'vue'
import VueRouter, {Route} from 'vue-router';
declare module 'vue/types/vue' {
interface Vue {
$router: VueRouter; // 這表示this下有這個東西
$route: Route;
}
}複製代碼
二、main.ts 的設置
// main.ts
import { Component } from "vue-class-component";
Vue.config.productionTip = false;
Component.registerHooks([
"beforeRouteEnter", //進入路由以前
"beforeRouteLeave", //離開路由以前
"beforeRouteUpdate"
]);複製代碼
三、須要監聽路由鉤子的 SCF 組件:
<script lang="ts">
// xxx.vue 的script標籤內
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import { Route, RawLocation } from 'vue-router';
// # 下邊兩段,看你須要什麼了:
// 1/監聽路由變化
@Watch('$route',{ immediate: true })
private changeRouter(route: Route){
console.log(route)
}
// 2/定義路由鉤子函數
private beforeRouteEnter(to: Route, from: Route, next: () => void): void {
console.log('beforeRouteEnter', to, from, next)
next(); // 沒有next將不會進入路由內部,跟vue文檔用法一致
}
private beforeRouteUpdate(to: Route, from: Route, next: () => void): void {
console.log('beforeRouteUpdate'); // 暫時不生效,版本問題
next();
}
private beforeRouteLeave(to: Route, from: Route, next: () => void): void {
console.log('beforeRouteLeave');
next();
}
</script>複製代碼
監聽路由的第二種寫法 (若是隻是想更新視圖的話能夠考慮監聽路由)
@Watch('$route')
routeWatch() {
this.loadData();
}複製代碼
基本同上 一、shims-vue.d.ts 的設置
// shims-vue.d.ts
import Vue from 'vue'
import VueRouter, {Route} from 'vue-router';
declare module 'vue/types/vue' {
interface Vue {
$router: VueRouter; // 這表示this下有這個東西
$route: Route;
}
}複製代碼
二、main.ts 的設置
// main.ts
import { Component } from "vue-class-component";
Component.registerHooks([
"beforeRouteEnter", //進入路由以前
"beforeRouteLeave", //離開路由以前
"beforeRouteUpdate"
]);複製代碼
三、須要監聽路由鉤子的 SCF 組件:
<script lang="ts">
// xxx.vue 的script標籤內
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import { Route, RawLocation } from 'vue-router';
// # 下邊兩段,看你須要什麼了:
// 1/監聽路由變化
@Watch('$route',{ immediate: true })
private changeRouter(route: Route){
console.log(route)
}
// 2/定義路由鉤子函數
private beforeRouteEnter(to: Route, from: Route, next: () => void): void {
console.log('beforeRouteEnter', to, from, next)
next(); // 沒有next將不會進入路由內部,跟vue文檔用法一致
}
private beforeRouteUpdate(to: Route, from: Route, next: () => void): void {
console.log('beforeRouteUpdate'); // 暫時不生效,版本問題
next();
}
private beforeRouteLeave(to: Route, from: Route, next: () => void): void {
console.log('beforeRouteLeave');
next();
}
</script>複製代碼
父組件內部: 一、調用子組件、並綁定傳值:
<ZiZuJian @chuanDiGuoQu="FuQinZiJiYong"></ZiZuJian>複製代碼
準備好一會會被子組件觸發的函數:
FuQinZiJiYong(){
console.log('我是父親內部待被觸發的方法')
}複製代碼
子組件 ZiZuJian 內部在須要觸發的地方執行$emit
export default class Menu extends Vue {
// 在須要觸發的地方,執行以下代碼
this.$emit('chuanDiGuoQu', '')
}複製代碼
最後還有另外一種網友總結很麻煩的寫法:參見地址
第一種:github 找到的 demo 這樣。以下代碼中hideHeader
就是由默認參數的父組件傳過來的屬性
export default class ComponentName extends Vue {
@Prop({
type: Boolean,
required: false,
default: false // 默認屬性的默認值
})
private hideHeader!: boolean | undefined
}複製代碼
第二種:vue 原生的寫法,並寫到了@component 構造器中就行了: 若是不傳值此函數默認就是 true,傳 false 就是 false 了。而且能嚴格判斷只能傳 Boolean 類型。挺好。
@Component({
props: {
hideHeader: {
type: Boolean,
required: false,
default: false // 默認屬性的默認值
}
}
})複製代碼
// 待解決複製代碼
安裝
npm i -S vue-echarts echarts複製代碼
main.ts 中引入並註冊
// main.ts
// 引用
import ECharts from "vue-echarts";
// 用到的模塊要單獨引用
import "echarts/lib/chart/line"; // 線圖爲例,其餘圖同樣
import "echarts/lib/component/title.js"; // 標題
import "echarts/lib/component/legend"; // 圖例
import "echarts/lib/component/tooltip"; // 提示框
import "echarts/lib/component/toolbox"; // 工具(以下載功能與按鈕)
// 註冊
Vue.component("v-chart", ECharts);複製代碼
vue.config.js 中設置
// vue.config.js
module.exports = {
// For Vue CLI 3+, add vue-echarts and resize-detector into transpileDependencies in vue.config.js like this:
transpileDependencies: ["vue-echarts", "resize-detector"]
};複製代碼
tsconfig.json 中也要設置
// tsconfig.json
{
"compilerOptions": {
"types": ["webpack-env", "echarts"]
}
}複製代碼
SFC 應用
<v-chart :options="echartsOptions" id="myCharts" ref="myCharts" />複製代碼
// main.ts
import ElementUI from "element-ui";
Vue.use(ElementUI);複製代碼
在 assets/styles 下新建_variable.scss 文件,用於存放 scss 變量。 而後再 vue.config.js 中設置全局變量
// vue.config.js
module.exports = {
css: {
loaderOptions: {
sass: {
prependData: ` @import "@/assets/styles/_variable.scss"; `
}
}
}
};複製代碼
同時解決問題alias 配置的路徑別名,在 vscode 中報錯模塊查找失敗
和問題vue-cli 配置了 resolve alias 來聲明的路徑別名,在引用了 ts 後,vscode 會報錯不能識別、模塊查找失敗
。其中,vscode 報錯在 win 環境還須要一個插件安裝,解決方案見下邊 vue.config.js 配置
// vue.config.js
module.exports = {
chainWebpack: config => {
// 別名配置
config.resolve.alias
.set("comp", resolve("src/components"))
.set("css", resolve("src/assets/styles"));
// ...同上,路徑覈對好就行
}
};複製代碼
jsconfig.json 配置。注意這裏的名字要和上邊 set 後邊的名字保持一致
// jsconfig.json
{
"compilerOptions": {
"paths": {
"@/*": [
"src/*" // 這個原本就有
],
// 後邊追加
"comp/*": [
"src/components/*"
],
"css/*": [
"src/assets/styles/*"
],
// ... 同上,路徑覈對好就行
},
}
};複製代碼
SCF 使用設定的別名
// main.ts
import MyError from "view/error/Error.vue";複製代碼
/* SCF單頁中scss路徑引用 */
@import "css/_variable.scss";複製代碼
vue.config.js 配置
// vue.config.js
module.exports = {
devServer: {
proxy: {
"/api": {
target: "http://11.11.11.111/", // 示例ip地址,也能夠填域名,須要的是後端接口地址的相同部分
changeOrigin: true,
pathRewrite: {
"^/api": ""
}
}
}
}
};複製代碼
axios 請求地址時的寫法: 注意/api
必定要有,且在路徑的最前邊,代替相同的路徑。
axios
.get("/api/wo/de/di/zhi") // 前邊的'/api'必定要有,它表明的就是vue.config.js中proxy.target的路徑
.then(() => {
// 接口成功...
});複製代碼
vue.config.js 配置
// vue.config.js
module.exports = {
devServer: {
disableHostCheck: true, // 用域名代替localhost,禁用主機檢查
host: "www.haha.com"
// 另外端口也能夠在這裏改,只不過我寫到了package.json總,見下邊
}
};複製代碼
package.json dev 命令的配置
{
"scripts": {
"dev": "npm run serve",
"serve": "vue-cli-service serve --port 80 --open", # 端口設置爲80,--open運行完畢後自動打開地址
}
}複製代碼
本地 host 配置
127.0.0.1 www.haha.com # 這裏注意和vue.config.js中的host的值對應複製代碼
此時,npm run dev
成功後,瀏覽器跑項目輸入地址http://www.haha.com
便可
一、擴展商店安裝插件 - Path Intellisense
二、配置代碼(vscode setting.json 中設置)
"path-intellisense.mappings": {
"@": "\${workspaceRoot}/src"
}複製代碼
三、在 package.json 統計目錄下建立 jsconfig.json 文件,並填入下邊代碼
// jsconfig.json
{
"compilerOptions": {
"paths": {
"@/*": ["src/*"]
}
}
}複製代碼
持續更新中...