如何使用打字稿在vue3中手动定义道具类型

时间:2020-08-10 06:36:56

标签: vue.js vuejs3

我能做

 $stateProvider.state('index.cars', {
            url: '/cars',
            templateUrl: 'partials/cars/index.html',
            controller: function($scope) {
              //get menu name of car page from api
              $scope.foo='menuName';
            },
            ncyBreadcrumb: {
              label: 'State {{foo}}'
            }
          })

告诉vue3我的defineComponent({ props: { name: { type: String as PropType<string> } } }) 类型是props,但是如果我有多个组件具有相同的props类型,我该如何共享定义?

如果我在:中定义道具,

{ name: string }

然后像这样使用它:

const props = {
  name: String as PropType<string>
}

它不起作用,我在道具设置功能中输入的类型不正确。

3 个答案:

答案 0 :(得分:1)

defineComponent 提供的 props 选项是一个纯 js 对象,仅用于类型注释,因此您可以使用 javascript 中的任何技术在对象之间共享结构:

// in common.ts
export const commonProps = {
  name: { type: String as PropType<string> }
}

// in your component.vue
import commonProps from "./common.ts";

defineComponent({
  props:{
    ...commonProps,

    extra: { }

  }
})

答案 1 :(得分:0)

尝试按照本文所述,在src文件夹的mixins文件夹中进行mixin https://vuejs.org/v2/guide/mixins.html#Basics 在那里,您只需要定义

export const propsMixin= {
     props: {
        name: { type: String as PropType<string> }
      }
}

,然后通过将此混入包含到您的组件中,将其用于您所尊敬的组件中

import {propsMixin} from '@mixins/propsMixin'

并将其包含到mixins数组中

mixins:[propsMixin]

答案 2 :(得分:0)

如果您在Vue 2中使用了成分API以准备切换到Vue 3,则必须使用该软件包中的PropType而不是vue软件包。

// Wrong for Vue 2
import Vue, { PropType } from 'vue'
import { defineComponent } from '@vue/composition-api'

// Right for Vue 2
import { defineComponent, PropType } from '@vue/composition-api'