亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

vue3編寫組件的幾種實(shí)現(xiàn)方式

 更新時(shí)間:2023年06月30日 09:19:06   作者:lethe_R  
這篇文章主要介紹了vue3編寫組件的幾種實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

一、選項(xiàng)式寫法

在 vue2.x 項(xiàng)目中使用的寫法就是選項(xiàng)API的寫法

(說明:類似于與vue2中的data里面寫的是定義的數(shù)據(jù),methods里面寫的是處理數(shù)據(jù)的方法,每一個(gè)選項(xiàng)都只負(fù)責(zé)自己的部分)

  • 優(yōu)點(diǎn):易于學(xué)習(xí),代碼位置固定,便于閱讀;
  • 缺點(diǎn):代碼組織性差,相似的邏輯代碼不便于復(fù)用;

vue3的選項(xiàng)式寫法中也可以有vue2的寫法

如果是新項(xiàng)目,應(yīng)只選擇vue3的寫法(這里指vue3的項(xiàng)目)

代碼如下:

<template>
  <div>
    <div>
      num3: {{ num3 }}
    </div>
    <div>
      num2: {{ num2 }}
    </div>
  </div>
</template>
// 類似于vue2中,data中定義數(shù)據(jù),methods就寫方法,每一個(gè)選項(xiàng)就寫對(duì)應(yīng)所負(fù)責(zé)的東西
<script>
import { ref } from "vue";
export default {
  // vue3代碼
  props: {
    testProps: {
      type: Number,
      default: () => {
        return 123456;
      },
    },
  }, // 接收傳過來的數(shù)據(jù)
  setup(props, context) {
    console.log("setup的props", props); // 父組件傳遞過來的數(shù)據(jù),但是前提是需要在props進(jìn)行數(shù)據(jù)的接收,否則無法使用
    console.log("testProps", props.testProps); // 123456
    console.log("setup的context", context);
    const num3 = ref(1);
    const addV3 = () => {
      num3.value++;
    };
    return { num3, addV3 }; // 使用選項(xiàng)式寫法這里必須將數(shù)據(jù)return出去
  },
  // vue2代碼
  data() {
    return {
      num2: 456,
    };
  },
  methods: {
    addV2() {
      this.num2++; // 這里面是可以使用this的,但是setup中不可以使用this
    },
  },
  mounted() {},
};
</script>

二、組合式寫法

組合式寫法(vue3特有的寫法)

  • 優(yōu)點(diǎn):一個(gè)功能邏輯的代碼組織寫在一起的,便于閱讀和維護(hù);
  • 缺點(diǎn):需要有良好的代碼組織能力和拆分邏輯能力;

說明:使用選項(xiàng)式的寫法寫vue3里面可以有vue2的代碼,但是如果采用vue3語法糖的寫法里面是不能有vue2的寫法的;

<template>
  <div>
    <div>
      num: {{ num }}
    </div>
    <div>
      comValue: {{ comValue }}
    </div>
  </div>
</template>
// 組合式寫法
<script setup> // vue3的語法糖
import { computed, ref } from "vue";
const num = ref(123);
const comValue = computed(() => {
  return num.value = num.value + 1;
})
const add = () => {
    num.value++ // 使用ref定義的值需要使用點(diǎn)value的形式進(jìn)行取值
}
console.log(comValue.value); // 124
</script>

三、JSX寫法

使用defineComponent來書寫組件的代碼

<template>
  <div>
    <div>
      num: {{ num }}
    </div>
  </div>
</template>
<script>
import { defineComponent, ref } from "vue";
// 在defineComponent使用vue3+vue2寫法
export default defineComponent({
  setup() {
    const num = ref(12);
    return {
      num
    }
  },
  data() {
    return { count: 1 }
  },
  methods: {
    increment() {
      this.count++;
    }
  }
})
// 直接在defineComponent使用vue3寫法
// export default defineComponent(() =>{
//   const count = ref(0)
//   return { count }
// })
</script>

總結(jié)

雖然vue3出來也有一段時(shí)間了,但是很多項(xiàng)目還是用的vue2,我覺得我們也應(yīng)該慢慢的去使用vue3了,從vue2到vue3的過渡,要養(yǎng)成一個(gè)良好的編碼習(xí)慣;建議使用vue3組合式的語法糖寫法。

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論