全局注册
- 全局注册的组件在注册后可以用于任意实例或组件中。
- 注意:全局注册必须设置在根 Vue 实例创建之前Vue.component(‘组件名’,{ /* 选项对象 / })例如Vue.component(‘my-component’,{ template:’全局组件‘ }) new Vue({ el:”#app”, data:{ } })<div id=”app”> <my-component><my-component> </div>组件基础
- 本质上,组件是可复用的 Vue 实例,所以它们可与new Vue 接收相同的选项,例如data、method以及生命周期钩子等。
- 仅有的例外是像 el 这样根实例特有的选项。
- 组件基础中主要讲解:组件命名规则,template选项,data选项
- 组件命名规则(创建组件时的设置规则)
- kebab-case:”my-component”
- PascalCase:”MyComponent”
注意:无论采用哪种命名方式,在DOM中都只有kebab-case可以使用。
Vue.component(‘my-component-a’,{ template:’<div>全局组件</div>’ }) Vue.component(‘MyComponentB‘,{ template:’<div>全局组件</div>’ })
- template选项
- template选项用于设置组件的结构,最终被引入根实例或其他组件中。
- 模板中语法与根实例中结构一致,可以执行vue相关指令操作,插值表达式等
- template只能有一个根元素Vue.component(“MyComponentA”,{ template:
<div> <h3>组件A 的标题内容 {{ 1+2*3 }}</h3> </div>})
- data选项
- data选项用于存储组件的数据,与根实例不同,组件的 data选项必须为函数,数据设置在返回值对象中。
- 组件并不一定是单个出现(一个组件一个功能的封装),为了确保多个组件实例内的数据是相互独立的而不是共用的,需要通过作用域隔离
- 函数内部拥有独立作用域,函数多次调用,形成多个内部独立作用域,作用域内数据不会相互影响
- 这种实现方式是为了确保每个组件实例可以维护一份被返回对象的独立的拷贝,不会相互影响。Vue.component(“MyComA”,{ template:
<div> <h3> {{ title }} </h3> <p> {{ content }} </p> </div>, data:function(){ return { title:’标题’, content:’内容’ } } })
每个组件都是独立的,修改某个组件实例数据,其他不会被影响
局部注册
- 局部注册的组件只能用在当前实例或组件中。
- 注意 DOM 写法永远 kebab-case
- components内组件 键名是 kebab-case 带连字符要加引号new Vue({ … components:{ ‘my-component-a’:{ template:’{{ title }}‘ data(){ return { title:”a title 内容” } } }, ‘MyComponentB’:{ template:’{{ title }}‘ data(){ return { title:”b title 内容” } } } } })
// ok // ok - 局部注册方式2:单独配置组件选项对象var MyComA = { } // 将选项对象放在对象中 var MyComB = { } new Vue({ el:”#app”, components:{ ‘my-com-a’:MyComA, MyComB:MyComB // ES6 简写成 MyComB } })
