必须要求Vue组件TWICE

问题描述 投票:0回答:1

我有一个简短的问题:基于下面的代码,为什么我必须“导入”下面的组件两次以使我的代码工作?

我在一个非常锁定的环境中工作,因此目前不能使用Webpack或.vue SFC,或者npm(用于所有意图和目的)。

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

我必须导入组件文件,然后将其作为组件。如果可以的话,我想清理一下,因为我们将把它作为P.O.C.开发人员也只是学习Vue,所以如果可以的话,我想在一开始就避免不良做法。

index.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"
},

});

App.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 }                                 <-----
});

的index.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-mvc typescript vue.js require
1个回答
1
投票

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

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

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

components: { Apple}

理论上你的应用程序应该仍然有效。

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

App.ts

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

index.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

© www.soinside.com 2019 - 2024. All rights reserved.