首页 > 解决方案 > 必须两次需要 Vue 组件

问题描述

我有一个简短的问题:根据下面的代码,为什么我必须两次“导入”下面的组件才能让我的代码工作

我在一个相当封闭的环境中工作,所以目前不能使用 Webpack 或 .vue SFC,或 npm(出于所有意图和目的)。

我已经使用打字稿文件拼凑了一个小型 vue 应用程序的工作版本,但我很困惑它为什么工作:S。

我必须导入组件文件,然后将其作为组件需要。 如果可以的话,我想把它清理掉,因为我们将把它作为一个 POC 与刚刚学习 Vue 的开发人员一起推出,所以如果可以的话,我想在一开始就避免不良做法。

索引.ts

import * as Vue from "vue";
import * as Apple from "./App";                  <-----  
Vue.component('apple2', Apple.default);          <-----  wat?

let v = new Vue({
el: "#app",
components: { Apple},                            <-----
template: `
<div>
    <apple2/>                                    <-----
</div>`,
data: {
    name: "World"
},

});

应用程序.ts

import * as  Vue from "vue";
import * as fred from  "./Hello";                    <----
Vue.component('fred2', fred.default);                <----

export default Vue.extend({
name: 'Apple',
template: `
<div>
    <fred2 :name="name" :initialEnthusiasm="4"/>     <-----
</div>`,
data() {
    return { name: "World" }
},
components: { fred }                                 <-----
});

索引.html

<!doctype html>
<html>
<head>
  <script src="scripts/vue.min.js"></script>
  <script data-main="scripts/build/index" src="scripts/lib/require.min.js"> 
  </script></head>
   <body>
     <div id="app"></div>
   </body>

tsConfig

{"compileOnSave": true,
"compilerOptions": {
"module": "amd",
"moduleResolution": "node",
"noImplicitAny": true,
"noEmitOnError": false,
"outDir": "./scripts/build",
"removeComments": false,
"sourceMap": true,
"target": "es5",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true
},
"exclude": [
"node_modules",
"wwwroot"
],
"include": [
"./scripts/**/*"
]

}

标签: asp.net-mvctypescriptvue.jsrequire

解决方案


当你这样做时,你混合了两个不同的概念:

Vue.component('apple2', Apple.default);

您实际上是在全局 Vue 实例中注册名为 apple2 的组件定义对象 (Apple.default),使其可用于之前引用的 Vue 实例呈现的所有组件。在这种情况下,您可以在 index.ts 中删除这部分代码:

components: { Apple}

从理论上讲,您的应用程序应该仍然可以工作。

但是因为您使用的是 typescript,您可以让您的应用程序像使用模块系统一样工作,允许您在每个父组件中导入使用的子组件,允许您执行以下操作:

应用程序.ts

export default const component = {
    template: '<div>My component</div>'
}

索引.ts

import Vue from 'vue';
import component from './App';

new Vue({
    el: '#app',
    components: {
        'my-imported-component': component
    }
});

在您的模板中:

<div id="app">
    <my-imported-component/>
</div>

在我看来,这将是一种更好的方法,因为您不会用所有组件污染全局 Vue 实例,但这是一个品味问题以及适合您的场景的问题。

有关更多信息,请查看此链接:
https ://vuejs.org/v2/guide/components-registration.html


推荐阅读