vue3.0新特性之setup

vue3.0新增了組合式API。今天想分享一下這個組合式API的使用場景以及使用方法。javascript

使用場景:當咱們的組件功能比較多的時候,對於相同邏輯的關注點的相關代碼會比較分散,可能分佈在生命週期鉤子、watch、computed等,會增長咱們對組件的理解以及維護。vue

解決辦法:咱們能夠在組件中配置setup,將這些代碼封裝在一塊兒。在執行setup時,組件是沒有實例化的,因此沒有this,也不能訪問組件本地的狀態、計算屬性和方法。setup的返回內容能夠暴露給組件的計算屬性、方法、生命週期鉤子、模板使用。經過ref建立一個響應式引用,使響應式變量在任何地方起做用。經過on+生命週期名字,能夠在setup中註冊生命週期鉤子;能夠添加watch、computed等。java

<template>
  <div class="hello">
    <!-- count 是setup中返回的count,能夠使用在組件的模板中,並支持響應式 -->
    <h1>{{count}}</h1>
    <!-- 在組件的模板中,能夠使用setup返回的add方法 -->
    <button @click="add()">add count</button>
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
import { onMounted, ref, watch } from 'vue';
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data(){
    return {
    }
  },
  setup(){
    let count = ref(0);
    let add = ()=>{
      count.value++;
    }
    let sum = ()=>{
      return 1+2;
    }
    watch(count,(val, old)=>{ // 在setup中添加watch
      console.log(count.value);
      console.log(old);
      console.log(val);
    })
    onMounted(add);// 在setup中註冊生命週期鉤子
    return { 
      //setup 返回的變量和方法能夠在當前組件的計算屬性、方法、生命週期鉤子以及模板中使用
      count,
      add,
      sum
    }
  },
  created(){
    // setup 返回的方法能夠用在生命週期鉤子中
    console.log(this.sum());
  }
}
</script>
 
<style scoped>
h3 {
  margin: 40px 0 0;
}
</style>
相關文章
相關標籤/搜索