Vue 3.0 setup 語法糖嘗試


Vue3.0 簡介

Vue3.0 正式版已經發布一段時間了,除了擁抱函數式編程,還帶來了新的語法糖,用以替代原本需要大量 return 的寫法

基礎用法

想要使用 setup 模式只要在 script 標簽上面加個 setup 屬性就可以了。這個模式下不需要 return 和 export 就可以在模板中使用。

<template>
  <el-button @click="handleClick">按鈕</el-button>
</template>

<script lang="ts" setup>
  import { ElButton } from 'element-plus'

  function handleClick() {
    alert('點擊了按鈕!')
  }
</script>

使用 props、emit

<template>
  <input :value="msg" @change="changeValue" />
</template>

<script lang="ts" setup>
  import { defineProps, defineEmits } from 'vue'

  const props = defineProps({
    msg: {
      type: String,
      required: true
    }
  })
  const emit = defineEmits(['update:msg'])

  function changeValue(e: InputEvent) {
    emit('update:msg', e.target.value)
  }
</script>

使用生命周期鈎子

<script lang="ts" setup>
  import { onMounted, onUnmounted } from 'vue'

  onMounted(() => {
    console.log('mounted')
  })

  onUnmounted(() => {
    console.log('unmounted')
  })
</script>

setup 語法糖的缺陷

  1. 這個語法糖暫時還不支持單文件導出內容,如果使用 export 導出模塊會導致編譯報錯。

  2. 不支持設置組件名,傳統的 options 寫法有個 name 屬性可以設置組件名,這個在編寫遞歸組件的時候很有用

  3. 不支持 jsx,不過如果需要使用 jsx 的話,個人還是建議直接使用傳統方式,setup 函數可以直接 return 一個 jsx 函數。而且 Vue 3.0 已經默認支持 css module 了,jsx 的體驗會比之前更好。

<script lang="tsx">
  import { defineComponent, ref, useCssModule } from 'vue'
  export default defineComponent({
    setup() {
      const msg = ref('Hello World')
      const style = useCssModule()

      return () => (
        <div class={style.parent}>
          <p class={style.text}>
            {{ msg.value }}
          </p>
        </div>
      )
    }
  })
</script>

<style module>
  .parent {
    background: #1890ff;
  }
  .text {
    color: red;
  }
</style>

寫在最后

這個特性其實還是實驗性質的,可能會有不少我暫時還沒遇到的奇怪 bug,所以不建議在生產環境使用。不過他確實可以精簡不少的代碼,特別是哪種內容比較豐富的頁面,盡管可以拆成多個子組件和 hooks,但是在拆分的比較多的情況下,引入模塊也不可避免地要寫一堆的模板代碼,相信這樣的編碼方式以后會成為 Vue 的標准范式。


免責聲明!

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



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