3、setup语法糖

setup 概述

setupVue3中一个新的配置项,值是一个函数,它是 Composition API 件中所用到的:数据、方法、计算属性、监视......等等,均配置在setup中。

特点如下:

  • setup函数返回的对象中的内容,可直接在模板中使用。
  • setup中访问thisundefined
  • setup函数会在beforeCreate之前调用,它是“领先”所有钩子执行的

使用

<script setup lang="ts" name="Student">

其中name为组件名称。

代码

Student.vue

<template>
<div>
    <h2>{
   
   { name }}</h2>
    <h2>{
   
   { age }}</h2>
    <button @click="updateName">修改名字</button>
    <button @click="updateAge">修改年龄</button>
    <button @click="showPhone">显示联系方式</button>
</div>
</template>

<script setup lang="ts" name="Student">
    import { ref, Ref } from 'vue';
    let name=ref('weihu')
    let age=ref(18)
    function updateName(){
        name.value="李四"
    }
    function updateAge(){
        age.value+=1
    }
    function showPhone(){
        alert("18880709")
    }
</script>

<style scoped>

</style>

App.vue

<template>
  <Student/>
</template>

<script lang="ts">
  import Student from './components/Student.vue'

  export default {
    name:'App', //组件名
    components:{Student} //注册组件
  }
</script>

猜你喜欢

转载自blog.csdn.net/weixin_37306719/article/details/143402776