美文网首页
typeScript 在 Vue 中的使用

typeScript 在 Vue 中的使用

作者: shmaur | 来源:发表于2019-01-16 16:11 被阅读100次

        强类型的好处网上有很多,就可以直接参照了。
        有现有配好的方式:
        # vue + typescript 项目起手式

        记录一下在配置过程中发现的问题:
        现在使用 vue-cli 的模板,安装 ts-loader 的时候,安装的是最新版本,但是在 vue 下载的模板中是不支持的,如果需要支持,需要更新 webpack 版本。在安装 ts-loader 的时候,修改版本,为 3.5.0 的版本就好了。
        还有一个就是所有的参数都必须有类型,比如下面的代码我不写它是字符串的话,ts 是识别不了的,就不会在页面上打印出来。
        使用后是这样子:

<script lang="ts">
import { Vue, Component, Emit } from "vue-property-decorator";
@Component
export default class HelloWorld extends Vue {
  msg: String = "Welcome to Your Vue.js App"
  @Emit()
  getinfo(){
    console.log(this)
    
  }
  created () {
    this.getinfo()
  }

}
</script>

        下面简单介绍一下装饰器:用于类式 Vue 组件的 ECMAScript / TypeScript 装饰器
        vue-class-component
        如果你使用 Babel,则需要 babel-plugin-transform-decorators-legacy。如果使用 TypeScript,请启用--experimentalDecorators标志。
注意:

  1. methods 可以直接声明为类成员方法。
  2. 可以将计算属性声明为类属性访问器。
  3. Initial data可以声明为类属性(如果使用Babel,则需要babel-plugin-transform-class-properties)。
  4. datarender并且所有Vue生命周期钩子也可以直接声明为类成员方法,但是您不能在实例本身上调用它们。声明自定义方法时,应避免使用这些保留名称。
  5. 对于所有其他选项,将它们传递给装饰器函数。
    例子:
<template lang="pug">
  div
    input (v-model="msg")
    p prop: {{propMessage}}
    p msg: {{msg}}
    p helloMsg: {{helloMsg}}
    p computed msg: {{computedMsg}}
    button (@click="greet") Greet
</template>

<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'

@Component({
  props: {
    propMessage: String
  }
})
export default class App extends Vue {
  // 原来的data中的数据
  msg = 123

  // 使用 props 中的数据
  helloMsg = 'Hello, ' + this.propMessage

  // 然后就是vue的生命周期
  mounted () {
    this.greet()
  }

  // 计算属性computed
  get computedMsg () {
    return 'computed ' + this.msg
  }

  // 方法 method
  greet () {
    alert('greeting: ' + this.msg)
  }
}
</script>

相关文章

网友评论

      本文标题:typeScript 在 Vue 中的使用

      本文链接:https://www.haomeiwen.com/subject/uaumdqtx.html