这些天我看了vue文档,并学习了组件。
但有一件事让我困惑
医生说有一些方法可以注册组件。
全球登记
Vue.component('my-component', {
// options
})本地注册
var Child = {
template: '<div>A custom component!</div>'
}
new Vue({
// ...
components: {
// <my-component> will only be available in parent's template
'my-component': Child
}
})这些注册定义了组件的名称(命名为“my-component”),这是很酷的。
但是当我引用vue + webpack项目时,我发现他们喜欢使用下面的方式注册组件。
index.html
<!--index.html-->
<!doctype html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test-vue</title>
</head>
<body>
<div id="root"></div>
<script src="./bundle.js"></script>
</body>
</html>app.js
// app.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import App from './App.vue'
Vue.use(VueRouter);
Vue.use(VueResource);
new Vue({
el: '#root',
render: (h) => h(App)
});App.vue
<!--App.vue-->
<template>
<div id="app">
<div>Hello Vue</div>
</div>
</template>
<script>
export default {
}
</script>组件似乎没有描述它的名称,为什么组件仍然可以工作?
请帮帮忙。
发布于 2017-06-01 07:02:57
这是ES6中的一个新特性
var foo = 'bar';
var baz = {foo};
baz // {foo: "bar"}
// equal to
var baz = {foo: foo};如果直接将App分配给对象,则变量名是属性名。
发布于 2017-05-04 15:56:48
这是ES6模块。每个组件都保存在自己的文件中。此文件具有“默认导出”。这个出口是无名的。导入组件时,将其赋值给变量。这就是给它起一个名字的时候。
假设我有这样一个模块,my-component.vue
<!--my-component.vue-->
<template>
<div id="my-component">
<div>Hello</div>
</div>
</template>
<script>
export default {
}
</script>当我需要使用这个模块时,我将导入它,并给它命名。
<!--another-component.vue-->
<template>
<div id="app">
<div>Test</div>
<my-component></my-component>
</div>
</template>
<script>
import myComponent from 'my-component.vue'
export default {
components:{
'my-component':myComponent
}
}
</script>按照惯例,每次导入时都会使用相同的名称,以保持自己的正常状态。但是因为这是一个变量,你可以在技术上给它起任何你想要的名字。
<!--another-component.vue-->
<template>
<div id="app">
<div>Test</div>
<test-test-test-test></test-test-test-test>
</div>
</template>
<script>
import seeYouCanNameThisThingAnything from 'my-component.vue'
export default {
components:{
'test-test-test-test':seeYouCanNameThisThingAnything
}
}
</script>在这个模块系统中,特别是Vue模块系统中,组件不给自己命名。需要其他组件的组件将提供名称。通常,此名称将与文件名相同。
https://stackoverflow.com/questions/43781699
复制相似问题