美文网首页
2.setup的使用

2.setup的使用

作者: jesse28 | 来源:发表于2021-11-17 07:16 被阅读0次

    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函数只能是同步而不能是异步

    相关文章

      网友评论

          本文标题:2.setup的使用

          本文链接:https://www.haomeiwen.com/subject/ietltrtx.html