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 的标准范式。

posted @ 2021-06-29 09:36  彩铅  阅读(3417)  评论(0编辑  收藏  举报