Vue3-setup

87 阅读1分钟

只在初始化执行一次

setup是一个函数,只在初始化的时候执行一次,它会在beforeCreate之前执行一次

setup是所有Composition API的容器,以后大部分代码都是在setup函数中写

没有this

setup中没有this,以后开发都不用this了

vue3的this不再指向vue实例,访问this会是undefined

优先级

setup返回的数据会和data和methods进行合并,setup优先级更高

异步问题

setup不要写成async函数

因为setup函数必须返回一个json对象供模板使用,

如果setup是一个async函数,返回的将是一个promise对象

如果setup是一个async函数,那么该组件就成了一个异步组件,需要配合 Suapense组件才能使用,关于Suspense组件后面说

写法1

返回一个对象,对象中属性或方法,模板中可以直接使用

//Home.vue
<template>
  <p>a:{{a}}</p>
  <p>b:{{b}}</p>
<button @click="handle">按钮</button>
</template>

<script>
  import {defineComponent} from "vue";

  export default defineComponent({
    name:"Home",
    data(){
      return{
        a:1,
        b:2
      };
    },
    methods:{
      handle(){
        console.log("handle")
      }
    },
////////////////////////////////////////////////////////////////
    setup(){
      console.log("setup",this);//undefined
      const handle=()=>{
        console.log("handle");
      };
      return{
        a:1,
        b:2,
        handle,
      };
    };
  })
</script>

写法2

这种比较方便,不用引入defineComponent,不用写return

<template>
  {{a}}
</template>
<script setup lang="ts">
  let a=111

  const handle=()=>{
    console.log(a)
  }
</script>