vue-property-decorator vue typescript寫法

什麼是Typescript

TypeScript 是一種由微軟開發的自由和開源的編程語言,它是 JavaScript 的一個超集,擴展了 JavaScript 的語法。做者是安德斯大爺, Delphi、C# 之父(你大爺永遠是你大爺)。把弱類型語言改爲了強類型語言,擁有了靜態類型安全檢查, IDE 智能提示和追蹤,代碼重構簡單、可讀性強等特色。 如今VUE 也支持了 TypeScript ,面對安德斯大爺放出的這些大招,果斷用之。vue

安裝使用

使用 vue-cli 建立項目的時候 選擇Typescript就好了, 注意下幾個配置文件 image.png tsconfig.jsonnode

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

tslint.jsonwebpack

{
  "defaultSeverity": "warning",
  "extends": [
    "tslint:recommended"
  ],
  "linterOptions": {
    "exclude": [
      "node_modules/**"
    ]
  },
  "rules": {
    "quotemark": [true, "single"],
    "indent": [true, "spaces", 2],
    "interface-name": false,
    "ordered-imports": false,
    "object-literal-sort-keys": false,
    "no-consecutive-blank-lines": false,
    "no-console": false, //容許使用console
    "member-access": [true, "no-public"], //禁止指定公共可訪問性,由於這是默認值
    // "noImplicitAny": false, //容許參數而不聲明其類型
    "one-variable-per-declaration": false, //容許在同一聲明語句中使用多個變量定義
    "no-unused-expression": [true, "allow-fast-null-checks"], //容許使用邏輯運算符執行快速空檢查並執行反作用的方法或函數調用( 例如e && e.preventDefault())
    "curly": [true, "ignore-same-line"],
    "arrow-parens": [true, "ban-single-arg-parens"],
    "semicolon": [true, "never"],//是否提示沒必要要的分號
    "trailing-comma": [
      true,
      {
        "multiline": {
          "objects": "ignore",
          "arrays": "ignore",
          "functions": "ignore",
          "typeLiterals": "ignore"
        },
        "esSpecCompliant": true
      }
    ]
  }
}

重要的是怎麼在項目中使用Typescrit寫法

1:安裝npm install --save vue-property-decorator 此類庫提供了7個裝飾器web

  • @Emit
  • @Inject
  • @Model
  • @Prop
  • @Provide
  • @Watch
  • @Component 實現生成像原生 JavaScript class 那樣的聲明組件。

下面分別給出實例解釋其用法:vue-cli

  • @Component 組件聲明 原生寫法
import UploadImage from '@/components/UploadImage'

export default {
  name: 'user',
  components: { UploadImage },
  data() {
    return {
      name:"張三",
      sex: '男'
    }
  },
  methods: {
    funcA(params) {},
    funcB() {}
  }
}

使用Ts中寫法express

import UploadImage from '@/components/UploadImage'
import { Component, Vue, Provide } from 'vue-property-decorator'

@Component(name:"user",components:{UploadImage})
export default class user extends Vue{
    private name:string="張三"
    private sex:string="男"

    private funcA(params:any){}
    private funcB(){}
}

其中使用 @Component 聲明瞭 user組件 ,同時引用 子組件 UploadImage,寫在 Components 參數中。npm

  • @Prop 屬性聲明 在自定義組建中使用 原生寫法
export default{
    name:"upload",
    props:{
          value:{
               type:String,
               default:''
          }
    }
}

在ts中寫法編程

@Component()
export default class upload extends Vue{
       @Prop()
       private value:string='';
}
  • computed 計算屬性 這個很相似於c#中的 屬性概念,屬性值自己能夠經過計算得出。

原生寫法json

computed: {
    imageUrl() {
      return 'http://xxxx.xxxx.com/' + this.value;//value是定義的一個字段
    }
  },

在ts中寫法c#

get imageUrl(){
      return 'http://xxxx.xxxx.com/' + this.value;//value是定義的一個字段
}

template 中同樣使用{{imageUrl}}
  • @watch 用來監測Vue實例上的數據變更 若是對應一個對象,鍵是觀察表達式,值是對應回調,值也能夠是方法名,或者是對象,包含選項。
export default {
    name: 'index',
    data() {
      return {
        demo: {
          name: ''
        },
        value: ''
      };
    },
    computed: {
      newName() {
        return this.demo.name;
      }
    },
    watch: {
      newName(val) {
        this.value = val;
      }
    }
  };

ts寫法

export default class index extends Vue{
        demo:any={name:''};
        value:string='';

        get newName(){  
              return this.demo.name;
        }

        @watch('wnewName')
        wnewName(val){
                  this.value=val;
        }
}
  • emit 咱們知道,父組件是使用 props 傳遞數據給子組件,但若是子組件要把數據傳遞回去,應該怎樣作?那就是自定義事件!

每一個 Vue 實例都實現了事件接口(Events interface),即:

-   使用 $on(eventName) 監聽事件
-   使用 $emit(eventName)觸發事件
Vue.component('counter', {
  template: `
  <button v-on:click="increment">{{ counter }}</button>`,
  data() {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
});

new Vue({
  el: '#example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})

<div id="example">
  <p>{{ total }}</p>
  <counter v-on:increment="incrementTotal"></counter>
</div>

子組件自定義了個事件,而後把這個事件發射出去,父組件使用這個事件

相關文章
相關標籤/搜索