• VUE3中的setup


    简介

    • 所有的组合函数都在setup()中使用,它是所有Composition API的起点
    • setup()只在初始化时执行一次,它是整个Composition API的入口
    • setup:提供模板所需要的数据和函数
    • 在模版中使用的数据和函数,需要在 setup 返回
    • setup()中返回的对象中的属性或方法, 在模板中可以直接使用
    • setup()函数中不能使用this,因为this会指向undefined
    • setup()会在beforeCreated()和created()执行之前执行。

    示例

    从组件生命周期来看,它的执行在组件实例创建之前vue2.x的beforeCreate执行。这就意味着在setup函数中 this 还不是组件实例,this 此时是 undefined

    <template>
         生命周期
    </template>
    <script lang='ts'>
        export default {
            setup() {
                console.log("setup")
                console.log(this)
            },
            beforeCreate() {  //不建议使用
                console.log("beforeCreate")
                console.log(this)
            },
            created() { //不建议使用
                console.log("created")
                console.log(this)
            }
        }
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    结果:
    在这里插入图片描述

    示例

    模板中需要使用的数据和函数,需要在setup()中返回。

    <template>
      <h2>{{ count }}</h2>
      <button @click="addFun1">count++</button>
      <button @click="addFun2()">count++</button>
    </template>
    
    <script lang='ts'>
    import { ref } from 'vue'
    
    export default {
      setup() {
        const count = ref(10)
    
        const addFun1=()=> { // 函数定义方式一
          count.value++;
        }
    
        function addFun2() { //函数定义方式二
          count.value++;
        }
    
        return {
          count,
          addFun1,
          addFun2
        }
      }
    
    }
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    注:若要在setup内执行ref,toRefs, computed,watch,watchEffect等函数,需先引入

    import { toRefs, ref, onMounted, nextTick } from "vue";
    
    • 1

    setup可接受props、context两个参数,其中props是响应式数据,不能直接解构赋值;context不是响应式数据,可以直接解构赋值。

    示例:

    props:['test']
    setup(props,context){
    //const {test} = props //错
    const {test} = toRefs(props) //对
    const { attrs, slots, emit }= context //对
      return {
        test
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  • 相关阅读:
    什么是MapReduce?MapReduce整体架构搭建使用介绍
    kettle学习--基础--3.2--案例--将MySQL的数据转化为kettle指定的文件格式
    linux 应急响应工具整理列表
    Texlive2020 for win10 宏包更新
    【案例】光电兼修的Alpha Cen,如何应对上升期的甜蜜烦恼?
    【UVM实战 ===> Episode_1 】~ MCDF设计更新、AMBA标准接口、UVM验证环境更新
    Nvm 安装
    Flir Blackfly S USB3 工业相机:白平衡设置方法
    json转换
    第一章:JDBC操作数据库
  • 原文地址:https://blog.csdn.net/lianghecai52171314/article/details/125480068