Vue 3.0 的组件还是和 Vue 2.x 没有区别,需要注意的是 props 访问是在 setup 函数中

  1. // HelloWorld.vue
  2. <template>
  3. <div>
  4. {{msg}}
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. name: 'HelloWorld',
  10. props: {
  11. msg: {
  12. type: String,
  13. default: 'HelloWorld'
  14. }
  15. },
  16. setup(props, context) {
  17. console.log(props, context)
  18. }
  19. }
  20. </script>

setup 函数提供两个参数:props 和 context

props

props 是一个响应式的对象,它不能被解构,不然会失去其响应性

  1. // bad
  2. setup({msg}) {
  3. console.log(msg) // 失去了响应性
  4. }
  5. // good
  6. setup(props) {
  7. console.log(props.msg) // 具有响应性
  8. }

它还是和 Vue 2.x 一样是不能直接被手动修改,不然会抛出异常警告

context

setup 函数第二个参数是上下文对象,它只暴露了三个属性 attrs 、emit 、slots

  1. setup(props, context) {
  2. context.attrs
  3. context.emit
  4. context.slots
  5. }
  • attrs 可以访问组件上的属性
  • emit 和 Vue 2.x this.$emit 效果一样
  • slots 在 jsx 中使用

JSX

由于 vite 是可以直接支持 jsx 语法,所以我们也可以在项目中直接使用 jsx。需要使用 defineComponent 包裹来使其变成一个双向绑定数据的组件

  1. import { defineComponent } from 'vue';
  2. const Button = defineComponent({
  3. setup(props, { slots }) {
  4. return () => (
  5. <button class={'btn', `btn-${props.type}`}>
  6. {slots.default()}
  7. </button>
  8. )
  9. }
  10. })
  11. export default Button;