zoukankan      html  css  js  c++  java
  • [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事件处理中心的构想
    form的novalidate属性
    AOP思想在JS中的应用
    推行浏览器升级提示,从自己做起
    doT.js模板引擎
    关于JS获取元素宽度的一点儿思考
    类似百度图片,360图片页面的布局插件
    ASCII、Unicode、UTF-8编码关系
    python字符串格式化符号及转移字符含义
    python字符串的方法介绍
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7507040.html
Copyright © 2011-2022 走看看