Vue 3 的学习

132 阅读1分钟

vue3.0 正式版已发布七个月左右,社区生态已经逐步完善

目前已支持 vue3 的UI组件库
  • ant-design-vue antdv.com/docs/vue/in…
    ant-design-vue 是 Ant Design 的 Vue 实现,组件的风格与 Ant Design 保持同步

  • element-plus element-plus.gitee.io/#/zh-CN
    Element Plus,一套为开发者、设计师和产品经理准备的基于 Vue 3.0 的桌面端组件库

  • vant vant-contrib.gitee.io/vant/v3/#/z…
    轻量、可靠的移动端 Vue 组件库,目前 Vant 已完成了对 Vue 3.0 的适配工作,并发布了 Vant 3.0 版本

  • VueUse vueuse.org/
    基于composition组合api的常用集合

Vue3带来的新变化
  1. 性能提升
  • 首次渲染更快
  • diff算法更快
  • 内存占用更少
  • 打包体积变小
  1. 更好的Typescript支持
  2. Composition API(组合式API)
相关阅读
  1. Vue3 中文文档 vue3js.cn/docs/zh/
  2. Vue3 设计理念 vue3js.cn/vue-composi…

组合式API与OptionAPI区别

<template>
  <div>
    <!-- 功能一模板 -->
    <button @click="show">显示</button>
    <button @click="hide">隐藏</button>
    <div v-if="showDiv">一个被控制显隐的div</div>
  </div>
  <div>
    <!-- 功能二模板 -->
    <button @click="changeRed">红色</button>
    <button @click="changeYellow">蓝色</button>
    <div :style="`color:${fontColor}`">一个被控制字体颜色的的div</div>
  </div>
</template>

vue2.0写法

<script>
export default {
  name: 'App',
  data() {
    return {
      showDiv: true, // 功能一数据
      fontColor: '' // 功能二数据
    }
  },
  methods: {
    // 功能一方法
    show() {
      this.showDiv = true
    },
    hide() {
      this.showDiv = false
    },
    // 功能二方法
    changeRed() {
      this.fontColor = 'red'
    },
    changeYellow() {
      this.fontColor = 'blue'
    }
  }
}
</script>

vue2特点: 便于理解,特定的选项有特定的位置存放

不足:代码变得庞大之后,找代码需要上下翻找

Vue3.0 写法
//-写法1,代码量增加后同样会难以查找
<script>
import { ref } from 'vue'
export default {
  name: 'App',
  setup() {
    // 功能一
    const showDivFlag = ref(true)
    function show() {
      showDivFlag.value = true
    }
    function hide() {
      showDivFlag.value = false
    }
    // 功能二
    const fontColor = ref('')
    function changeRed() {
      fontColor.value = 'red'
    }
    function changeBlue() {
      fontColor.value = 'blue'
    }
    return { showDivFlag, show, hide, fontColor, changeRed, changeBlue }
  }
}
</script>

//-写法二
<script>
import { ref } from 'vue'
function useShow() {
  const showDivFlag = ref(true)
  function show() {
    showDivFlag.value = true
  }
  function hide() {
    showDivFlag.value = false
  }
  return { showDivFlag, show, hide }
}
function useColor() {
  const fontColor = ref('')
  function changeRed() {
    fontColor.value = 'red'
  }
  function changeBlue() {
    fontColor.value = 'blue'
  }
  return { fontColor, changeRed, changeBlue }
}
export default {
  name: 'App',
  setup() {
    // 功能一
    const { showDivFlag, show, hide } = useShow()
    // 功能二
    const { fontColor, changeRed, changeBlue } = useColor()
    return { showDivFlag, show, hide, fontColor, changeRed, changeBlue }
  }
}
</script>

vue3特点:可以将特定功能相关的数据和方法放在一起进行维护,还可以进行逻辑拆分处理