Vue3基础之setup

setup的基础使用

  • setup 是个函数
  • 是一个新的组件选项,所有的组合API函数都在此使用,作为在组件内使用 Composition API 的入口点,只在初始化时执行一次
  • setup 内部不存在this
  • setup 内部如果return出去一个对象,对象的数据或者方法,都能够在模板中直接使用
  • setup 相当于beforeCreat 和 created 这两个生命周期函数的合并
<template>
  <div class="about">
    <h1>This is an about page</h1>
    <p>count:{{count}}</p>
    <button @click="showCount">按钮</button>
  </div>
</template>

<script lang="ts">
import {defineComponent} from "vue";
export default defineComponent({
  name:"AboutView",
  setup(){
    //此定义变量方式没有响应式,vue3提供特殊的具备响应式的定义变量方法
    let count = 0;
    //内部虽然没有this,但是不影响箭头函数使用,箭头函数内本身也没有this
    //函数内部一定要写内容,不然报语法错误
    const showCount = () => {
        alert(1);
    };
    return {count,showCount}
  },
})
</script>

运行结果

vue3生命周期图谱:
支持选项式API 和 组合式API
当renderer遇到组件时,使用选项式API就使用beforeCreat 和 created,使用组合式API就使用setup函数

setup的高级使用

  • 语法糖setup函数
  • 直接写在script标签上,内部不需要return
<template>
  <div class="about">
    <h1>This is an about page</h1>
    <p>count:{{count}}</p>
    <button @click="showCount">按钮</button>
  </div>
</template>

<script lang="ts">
import {defineComponent} from "vue";
export default defineComponent({
name:"AboutView",
})
</script>
<script lang="ts" setup>
let count = 0;
const showCount = () => {
        alert(1);
   };
</script>

运行结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值