Vue3 TypeScript defineComponent 的代码演示

23 min read

Vue3中的defineComponent方法用于定义组件。下面是一个使用Vue3和TypeScript来定义一个简单组件的代码演示:

// 引入所需的库
import { defineComponent } from 'vue'

// 定义组件选项对象的类型
interface HelloProps {
  msg: string
}

// 使用defineComponent方法定义组件
export default defineComponent({
  // 组件的名字
  name: 'HelloWorld',
  // 组件的props选项
  props: {
    msg: {
      type: String,
      required: true
    }
  },
  // 组件的模板
  template: `
    <div class="hello">
      <h1>{{ msg }}</h1>
      <button @click="changeMsg">Change Message</button>
    </div>
  `,
  // 组件的方法
  methods: {
    changeMsg() {
      this.msg = 'Hello Vue3 + TypeScript!'
    }
  }
})

在上面的示例中,我们首先引入了defineComponent方法。然后定义了一个HelloProps接口来描述组件的props选项。接下来,使用defineComponent方法来定义组件,指定了组件的名字、props选项和模板。在模板中,我们使用了插值语法{{ msg }}来绑定msg属性,并在按钮的点击事件中调用了changeMsg方法来改变msg属性的值。

最后,我们使用export default将组件导出,以便在其他地方使用。