2.setup的使用

2021-11-17  本文已影响0人  jesse28

1.在vue3中定义变量和方法现在需要在setup当中定义,定义完之后如果想在template当中使用,需要return出去。

<template>
  <div class="welcome">
    <div class="container">
      欢迎你!!!!!{{count}}
      <button style="background:red;width:40px;height:40px" @click="myFn" ></button>
    </div>
     
  </div>
</template>

<script>
import { ref } from "vue"
export default {
  // setup函数是组合api的入口函数,注意在组合api中定义的变量或者方法,要在template响应式需要return{}出去
  setup(){
    let count = ref(33)
    function myFn(){
      count.value +=1
    }
    return {count,myFn}
  },
  
}
</script>

<style scoped lang="scss">
    .welcome{
      height: 100%;
       .container{
         display: flex;
         justify-content: center;
         align-items: center;
         height: 100%;
       }
    }
</style>

1.setup的执行时机
beforeCreate:组件被创建出来,组件的methods和data还没初始化好
setup :在beforeCreate和created之间执行
created:组件被创建出来,组件的methods和data已经初始化好了

2.setup注意点
&1:由于在执行setup的时候,created还没有创建好,所以在setup函数内我们是无法使用data和methods的。
&2:所以vue为了让我们避免错误的使用,直接将setup函数内的this执行指向undefined
&3:setup函数只能是同步而不能是异步

上一篇下一篇

猜你喜欢

热点阅读