未使用setup语法糖
<script lang="ts">
  export default {
    name: "App",
    setup() {
      let name = "张三"
      let age = 20
      function handleClick() {
        age += 1
      }
      
      return {
        name,
        age,
        handleClick,
      }
    }
  }
</script>
<template>
  <div class="class">
    <h1>Hello Vue 3</h1>
    <h2>姓名:{{ name }}</h2>
    <h2>年龄:{{ age }}</h2>
    <button @click="handleClick">点击我,年龄+1</button>
  </div>
</template>
<style scoped>
  .class {
      color: red;
      font-size: 20px;
      height: 20%;
  }
  button {
      background-color: blue;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 5px;
      cursor: pointer;
  }
</style>
未使用setup语法糖前需要将定义的数据,方法等return出去,但是当定义的东西多了之后容易忘掉产生错误,因此可以使用语法糖的形式较为麻烦。
使用setup语法糖
<script lang="ts" setup>
    let name = "张三"
    let age = 20
    function handleClick() {
      age += 1
    }  
</script>
<script>
  export default {
    name: "Person",
  }
</script>
<template>
  <div class="class">
    <h1>Hello Vue 3</h1>
    <h2>姓名:{{ name }}</h2>
    <h2>年龄:{{ age }}</h2>
    <button @click="handleClick">点击我,年龄+1</button>
  </div>
</template>
<style scoped>
  .class {
      color: red;
      font-size: 20px;
      height: 20%;
  }
  button {
      background-color: blue;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 5px;
      cursor: pointer;
  }
</style>
其中第一个script标签用于设置数据,第二个script标签用于设置vue组件的名字,也可以用省略写法将两个script标签合成一个,但是要先安装一个插件
- 安装插件
  
- 修改vite.config.ts文件
  
 修改Vue组件, 将 lang=“ts” setup name=“Person234” 三个属性写到一起。
<script lang="ts" setup name="Person234">
    let name = "张三"
    let age = 20
    function handleClick() {
      age += 1
    }  
</script>
<template>
  <div class="class">
    <h1>Hello Vue 3</h1>
    <h2>姓名:{{ name }}</h2>
    <h2>年龄:{{ age }}</h2>
    <button @click="handleClick">点击我,年龄+1</button>
  </div>
</template>
<style scoped>
  .class {
      color: red;
      font-size: 20px;
      height: 20%;
  }
  button {
      background-color: blue;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 5px;
      cursor: pointer;
  }
</style>
修改完成后可以看到组件名称已经变成了Person234。
 



















