发表于: 2019-07-17 23:15:11

1 810


今天完成的事情:(一定要写非常细致的内容,比如说学会了盒子模型,了解了Margin) 
明天计划的事情:(一定要写非常细致的内容) 
遇到的问题:(遇到什么困难,怎么解决的) 
收获:(通过今天的学习,学到了什么知识)

1.组件名

注册一个组件的时候,我们始终需要给它一个名字。比如在全局注册的时候我们已经看到了:
Vue.component('my-component-name', { /* ... */ })
该组件名就是 Vue.component 的第一个参数。
我们强烈推荐遵循 W3C 规范中的自定义组件名 (字母全小写且必须包含一个连字符)。这会帮助你避免和当前以及未来的 HTML 元素相冲突。
2.组件名大小写
(1)使用 kebab-case (短横线分隔命名) 定义一个组件
(2)使用 PascalCase (首字母大写命名) 定义一个组件
<my-component-name> 和 <MyComponentName> 都是可接受的。注意,尽管如此,直接在 DOM (即非字符串的模板) 中使用时只有 kebab-case 是有效的。
3.全局注册
目前为止,我们只用过 Vue.component 来创建组件:
Vue.component('my-component-name', {  // ... 选项 ... })
这些组件是全局注册的。也就是说它们在注册之后可以用在任何新创建的 Vue 根实例 (new Vue) 的模板中。
new Vue({ el: '#app' })
<div id="app">  <component-a></component-a>  <component-b></component-b>  <component-c></component-c>    </div>
4.局部注册
全局注册所有的组件意味着即便你已经不再使用一个组件了,它仍然会被包含在你最终的构建结果中。这造成了用户下载的 JavaScript 的无谓的增加。
在这些情况下,你可以通过一个普通的 JavaScript 对象来定义组件:
var ComponentA = { /* ... */ } var ComponentB = { /* ... */ } var ComponentC = { /* ... */ }
然后在 components 选项中定义你想要使用的组件:
new Vue({  el: '#app',  components: {   'component-a': ComponentA,   'component-b': ComponentB  } })
局部注册的组件在其子组件中不可用。例如,如果你希望 ComponentA 在 ComponentB 中可用,则你需要这样写:
var ComponentA = { /* ... */ } var ComponentB = {  components: {   'component-a': ComponentA   },  // ... }
5.模块系统
(1)在模块系统中局部注册
我们推荐创建一个 components 目录,并将每个组件放置在其各自的文件中。
然后你需要在局部注册之前导入每个你想使用的组件。例如,在一个假设的 ComponentB.js 或 ComponentB.vue 文件中:
import ComponentA from './ComponentA'import ComponentC from './ComponentC'export default {  components: {    ComponentA,    ComponentC  },  // ...}
现在 ComponentA 和 ComponentC 都可以在 ComponentB 的模板中使用了。
(2)基础组件的自动化全局注册
可能你的许多组件只是包裹了一个输入框或按钮之类的元素,是相对通用的。我们有时候会把它们称为基础组件,它们会在各个组件中被频繁的用到。
就可以使用 require.context 只全局注册这些非常通用的基础组件。这里有一份可以让你在应用入口文件 (比如 src/main.js) 中全局导入基础组件的示例代码:
全局注册的行为必须在根 Vue 实例 (通过 new Vue) 创建之前发生



返回列表 返回列表
评论

    分享到