• [Vue + TS] Write a Vue Component as a Class in TypeScript


    Starter app: https://github.com/alexjoverm/Vue-Typescript-Starter

    Writing Vue components as plain objects has very limited capabilities for TypeScript’s IntelliSense. This lesson will show you how to write components as classes to take full potential of TypeScript static typing by using vue-class-component.

    Install: 

    npm install --save vue-class-component

    Original file:

    <template>
      <div class="hello">
        <h1>{{ message }}</h1>
        <button @click="clicked">Click</button>
      </div>
    </template>
    
    <script lang="ts">
    export default {
      data () {
        return {
          message: 'Welcome to Your Vue.js App'
        }
      },
    
      computed: {
        fullMessage(){
          return `${this.message} from Typescript`;
        }
      },
    
      created() {
        console.log('created');
      },
    
      methods: {
        clicked(){
          console.log('clicked');
        }
      }
    }
    </script>
    • Everything inside "data" mapping to props in class.
    • Everything inside "computed" mapping to get method
    • "created" lifecycle hook is just a function
    • Everything inside "methods" are also just functions.
    <template>
      <div class="hello">
        <h1>{{ message }}</h1>
        <button @click="clicked">Click</button>
      </div>
    </template>
    
    <script lang="ts">
    import Vue from 'vue'
    import Component from 'vue-class-component'
    
    @Component({})
    export default class Hello extends Vue {
      message: string = 'Welcome to Your Vue.js App'
    
      get fullMessage() {
        return `${this.message} from Typescript`
      }
    
      created() {
        console.log('created');
      }
    
      clicked(){
          console.log('clicked');
        }
    }
    
    /*
    export default {
      data () {
        return {
          message: 'Welcome to Your Vue.js App'
        }
      },
    
      computed: {
        fullMessage(){
          return `${this.message} from Typescript`;
        }
      },
    
      created() {
        console.log('created');
      },
    
      methods: {
        clicked(){
          console.log('clicked');
        }
      }
    }*/
    </script>
  • 相关阅读:
    JS中every()和some()的用法
    Git 各指令的本质
    vue登录3D效果
    vue打包后反编译到源代码(reverse-sourcemap)
    CSS Modules
    有了 HTTP 协议,为什么还需要 Websocket?
    微信小程序的实现原理
    JS
    微信小程序的发布流程
    中国地图
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7507040.html
Copyright © 2020-2023  润新知