Writing examples of Vue3+TS and Vue2+TS, with interface constraints added

The following are Vue3+TypeScript and Vue2+TypeScript writing examples, with interface constraints added:

Vue3+TypeScript

	<template>
	  <div>
	    <h1>{
    
    {
    
     title }}</h1>
	    <ul>
	      <li v-for="(item, index) in list" :key="index">{
    
    {
    
     item }}</li>
	    </ul>
	    <p>Count: {
    
    {
    
     count }}</p>
	    <button @click="increment">Increment</button>
	  </div>
	</template>
	
	<script lang="ts">
	import {
    
     defineComponent, ref } from 'vue'
	
	interface Props {
    
    
	  title: string;
	  list: string[];
	}
	
	export default defineComponent({
    
    
	  name: 'MyComponent',
	  props: {
    
    
	    title: {
    
    
	      type: String,
	      required: true
	    },
	    list: {
    
    
	      type: Array,
	      required: true
	    }
	  } as Props,
	  setup(props: Props) {
    
    
	    const count = ref(0)
	
	    const increment = () => {
    
    
	      count.value++
	    }
	
	    return {
    
    
	      count,
	      increment
	    }
	  }
	})
	</script>
	

Vue2+TypeScript


	<template>
	  <div>
	    <h1>{
    
    {
    
     title }}</h1>
	    <ul>
	      <li v-for="(item, index) in list" :key="index">{
    
    {
    
     item }}</li>
	    </ul>
	    <p>Count: {
    
    {
    
     count }}</p>
	    <button @click="increment">Increment</button>
	  </div>
	</template>
	
	<script lang="ts">
	import Vue from 'vue'
	
	interface Props {
    
    
	  title: string;
	  list: string[];
	}
	
	export default Vue.extend({
    
    
	  name: 'MyComponent',
	  props: {
    
    
	    title: {
    
    
	      type: String,
	      required: true
	    },
	    list: {
    
    
	      type: Array,
	      required: true
	    }
	  } as Props,
	  data() {
    
    
	    return {
    
    
	      count: 0
	    }
	  },
	  methods: {
    
    
	    increment() {
    
    
	      this.count++
	    }
	  }
	})
	</script>
	

** Note that the main difference between Vue3+TypeScript and Vue2+TypeScript is that Vue3 uses the setup function to replace the data and methods attributes of Vue2, and uses ref and reactive functions to implement responsive data. Vue3's component declaration method is more concise and requires less code. At the same time, TypeScript support in Vue3 is also more complete, including better type inference and better type definition.

** When defining the component, a Props interface is added to constrain props. Doing so can make it easier for us to perform type checking during development, and can also improve the readability and maintainability of the code.

おすすめ

転載: blog.csdn.net/weixin_44072916/article/details/129183313