首先看一下一个单文件vue文件

<template>
  <div class="home"></div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Home",
    setup(){},
  components: {},
});
</script>
如果在vue3中使用了TS,defineComponent 可以给予了组件 正确的参数类型推断。
函数的用法,可以代替 Vue2 中的 date 和 methods 属性,直接把逻辑写在 setup 里就可以

接下来我们写一个简单的小程序

<template>
  <div id="nav">
    <img alt="Vue logo" src="@/assets/logo.png" />
    <div>
    </div>
    <div>
      <button
        v-for="(item, index) in girls"
        :key="index"
        @click="selectGirlFun(index)"
      >
        {{ index }} : {{ item }}
      </button>
    </div>
    <div>你选择了【{{ selectGirl }}】</div>
  </div>
</template>
<script lang="ts">
//ref 函数的使用,它是一个神奇的函数,我们这节只是初次相遇,要在template中使用的变量,必须用ref包装一下。
import { defineComponent, reactive, toRefs } from "vue";

export default defineComponent({
  name: "App",
  // setup 函数的用法,可以代替 Vue2 中的 date 和 methods 属性,直接把逻辑卸载 setup 里就可以
  // reactive 用来解决需要返回多个值的问题,reactive后需要只需要return一个值
  // toRefs 用来解决使用时都要data.问题把data toRefs后不需要每次都data.一下
  setup() {
    interface DataProps {
      girls: string[];
      selectGirl: string;
      selectGirlFun: (index: number) => void;
    }
    const data: DataProps = reactive({
      girls: ["girl1", "girl2", "girl2"],
      selectGirl: "",
      selectGirlFun: (index: number) => {
        data.selectGirl = data.girls[index];
      },
    });
    const refData = toRefs(data);

    // return出去的数据和方法,在模板中才可以使用,这样可以精准的控制暴漏的变量和方法。
    return {
      ...refData,
    };
  },
});
</script>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
</style>