asp.net-mvc - 必须两次需要 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/**/*"
]
}
解决方案
当你这样做时,你混合了两个不同的概念:
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
推荐阅读
- python - 如何将 tf.Variable 转换为 numpy?
- matlab - 使用按钮单击中断循环 Appdesigner GUI [在调试模式下工作但不在正常模式下工作] [绘图和按钮都具有不同的功能]
- python - 在python中获取字符串值的正则表达式
- python - 如何将 Tkinter 8.6.8 升级到 8.6.9?
- reactjs - React route:如何从组件中获取当前的route key
- javascript - 即使窗口屏幕大小为
- c# - 从 .Net Core 中的启动配置方法调用控制器操作
- iso - 为 post-fd 操作系统(例如 CentOS 8)生成 kickstart ISO 并在打包程序 vsphere-iso 调用中使用它
- laravel - Laravel 8x 使用 JetStream Teams 创建用户表
- jupyter-notebook - 获取:启动 Jupyter 时“无法获取元数据”