vue的【選項式api】 vs 【組合式api】


前言

伴隨着新到的vue3,我們編寫組件的書寫方式也發生了變化。
除了底層的更新,編寫方式的改變 或許才是我們最能直觀感受到的。

其實就是vue3多了一種名為組合式api(composables api)的寫法,相對應的式傳統選項式api(options api)
組合式api簡單來說就是使用setup方式編寫組件

傳統的 選項式api

來看看這種傳統的寫法:65行

<template>
  <div class="home" v-if="userInfo">
    <my-header/>
    用戶詳情:{{fullUname}},{{userInfo.age}}歲
  </div>
</template>
<script>
import MyHeader from '../components/my-header.vue';

export default {
  // 組件:公共頭部
  components: { MyHeader },

  // 屬性: 接受屬性用戶id
  props: {
    userId: {
      type: String,
      default: '2022-01-01'
    }
  },

  // 狀態:用戶信息
  data() {
    return {
      userInfo: null
    }
  },

  // 計算屬性:給用戶名加一個牛逼的前綴
  computed: {
    fullUname() {
      if(this.userInfo && this.userInfo.name){
        return '牛逼的' + this.userInfo.name;
      }
      return ''
    }
  },

  // 監聽:用戶id改變
  watch: {
    userId: {
      handler(newVal, oldVal) {
        console.log('用戶id變化啦:'+newVal);
      },
      immediate: true
    }
  },

  // 方法:同步用戶信息
  methods: {
    syncUserInfo(userId) {
      this.userInfo = {
        id: userId,
        name: '小明',
        age: 20
      };
    }
  },

  // 鈎子:初始化
  mounted() {
    this.syncUserInfo(this.userId)
  }
}
</script>

先進的 組合式api

來看看這種先進的寫法:48行

<template>
  <div class="home" v-if="userInfo">
    <my-header />
    用戶詳情:{{ fullUname }},{{ userInfo.age }}歲
  </div>
</template>
<script setup>// <script setup> 是在單文件組件 (SFC) 中使用組合式 API 的編譯時語法糖。
import { ref, onMounted, watch, computed } from 'vue';
import MyHeader from '../components/my-header.vue';

// 屬性: 接受屬性用戶id
const props = defineProps({
  userId: {
    type: String,
    default: '2022-01-01'
  }
})

// 狀態:用戶信息
const userInfo = ref(null);

// 計算屬性:給用戶名加一個牛逼的前綴
const fullUname = computed(() => {
  if (userInfo.value && userInfo.value.name) {
    return '牛逼的' + userInfo.value.name;
  }
  return ''
})

// 監聽:用戶id改變
watch((newVal, oldVal) => {
  console.log('用戶id變化啦:' + newVal);
}, { immediate: true })

// 方法:同步用戶信息
const syncUserInfo = (userId) => {
  userInfo.value = {
    id: userId,
    name: '小明',
    age: 20
  };
}

// 鈎子:初始化
onMounted(() => {
  syncUserInfo(props.userId)
})
</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM