【问题标题】:is it necessary to import vue in all components? Nuxt and typescript是否有必要在所有组件中导入 vue? Nuxt 和打字稿
【发布时间】:2021-11-17 23:33:37
【问题描述】:

目前我已将 typescript 集成到 nuxt,如文档中所示:https://typescript.nuxtjs.org/es/guide/setup/

但我有以下疑问:在组件中,您应该始终 import vue from "vue"export default Vue.extend ({}); 在文档中我看到他们使用 1 个组件 (https://typescript.nuxtjs.org/es/cookbook/components) 执行示例,但就我而言,我有疑问如果我真的应该将它们添加到所有组件中,或者我可以以什么方式全局执行此操作。

我认为我在 types/vue-shim.d.ts 文件中的配置为我做了这个,但后来我的概念错了。

vue-shim.d.ts:

import Vue from "vue";
declare module "*.vue" {
  import Vue from "vue";
  export default Vue;
}

在将 typescript 添加到 nuxt 之前,我的组件是这样的:

<script>
import comp from "../component.vue";
export default {
  components: {
    comp
  },
  data() {
    return {
      createUser: true,
      params: {
        rol_id: 0,
        post_url: "",
        update_url: ""
      }
    };
  },
  mounted() {
    this.params.post_url = this.$config.routePrefix + "/agency/";
    this.params.update_url = this.$config.routePrefix + "/agency/";
    if (this.$route.params.uuid !== undefined) {
      this.createUser = false;
    }
  },
  methods: {
    fetchForms() {}
  }
};
</script>

【问题讨论】:

    标签: typescript vue.js vuejs2 nuxt.js


    【解决方案1】:

    不,并非绝对需要在所有组件中导入vue

    docs 中所述,Vue.extend 仅用于在 TypeScript IDE 中启用类型推断。例如,它让 TypeScript 根据 data() 中的 params 的声明来推断 mounted() 中的 this.params 的类型。

    Vue.extend 不添加任何功能,因此无论有无Vue.extend,您的组件都将运行相同。但是,要充分利用 TypeScript,您应该在组件中使用 Vue.extend

    【讨论】:

    • 我明白了,但是如何在 Visual Studio Code 中添加它?由于我收到诸如'Property'value'之类的错误不存在于类型上,即我在data () {return {value: ''}}中添加的错误
    • 为避免这些错误,您需要在组件中导入vue,并使用Vue.extend()
    • 有没有办法全局配置这个,以免每个组件都添加进去?
    • 不,目前不可能。
    猜你喜欢
    • 1970-01-01
    • 2019-08-28
    • 2020-07-08
    • 2020-10-30
    • 1970-01-01
    • 2018-07-28
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多