3

vue3中defineComponent 的作用

 1 year ago
source link: https://www.fly63.com/article/detial/12145
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

更新日期: 2022-09-19阅读: 9标签: 组件分享

扫一扫分享

vue3中,新增了 defineComponent ,它并没有实现任何的逻辑,只是把接收的 Object 直接返回,它的存在是完全让传入的整个对象获得对应的类型,它的存在就是完全为了服务 TypeScript 而存在的。

我都知道普通的组件就是一个普通的对象,既然是一个普通的对象,那自然就不会获得自动的提示,

import { defineComponent } from 'vue'

const component = {
name: 'Home',
props:{
data: String,
},
setup // 没有该有的提示,这非常的不友好
}

export default component

但是当我们加上 defineComponent() 之后,就完全不一样了,可以获得自动提示,vue2、vue3的自动提示都有

import { defineComponent } from 'vue'

const component = {
  name: 'Home',
  props:{
    data: String,
  },
  setup(){
    // setup 可接受两个参数,一个props,和 context
  }
}

export default component

接下来看看 setup 中的两个参数 props 与 context ,
props指组件传递来的参数,并且ts可以推论出props的类型.props也就是 vue2 中组件中的 props
context 有三个属性 attrs slots emit 分别对应vue2中的 attrs属性、slots插槽、$emit发送事件

import { defineComponent } from 'vue'

const component = {
name: 'Home',
props:{
data: String,
},
setup(props, context){
// props.data
// context.attrs context.slots context.emit
}
}

export default component

链接: https://www.fly63.com/article/detial/12145


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK