1️⃣ 创建组件
// 使用 extend 创建let compOne = Vue.extend({data() {return {};},template: "<div></div>",});// 使用 component 创建传模板Vue.component('comp-two', {data() {return {};},template: "<div> comp-two </div>",});// 使用 component 创建传选择器<body><div id="app"></div>/* template 必须在挂载的元素之外*/<template id="comp-three">template</template></body>Vue.component('comp-three', {data() {return {};},template: "#comp-three", // 可以传入一个选择器});
2️⃣ 全局组件
在注册一个组件的时候,我们始终需要给它一个名字。
1. 组件名就是定义组件的第一个参数,第二个参数是组件的构造函数,可以是 Function,可以是 Object
Vue.component('my-component', {data() {return {}},template:`<div>......</div>`})
但在一些工程化的大型项目中,很多组件都不需要全局使用。 比如一个登录组件,只有在登录的相关页面中使用,如果全局注册,将导致构建工具无法优化打包 因此,除非组件特别通用,否则不建议使用全局注册
2️⃣ 局部组件
不需要每个组件都全局注册,可以让组件只能用在其他组件内。我们可以用实例选择 components 注册。
1. 对于 components 对象中的每一个属性来说,其属性名就是自定义元素的名字,其属性值就是这个组件的选项对象。
// 局部组件注册 - 方式一const myComponent = {template: `<div>局部组件注册 - 方式一</div>`}// Vue 实例const vm = new Vue({el: "#app",components: {myComponent,// 局部组件注册 - 方式二'my-component-2': {template: `<div>局部组件注册 - 方式二</div>`}}});
2️⃣ 全局组件和局部组件的差别
全局组件的 this 指向 window
局部组件的 this 指向 vue 的实例对象
1️⃣ 应用组件
在模板中使用组件特别简单,把组件名当作HTML元素名使用即可。
在 components 中注册组件
但要注意以下几点:
2️⃣ 组件必须有结束
组件可以自结束,也可以用结束标记结束,但必须要有结束
<template><div id="app"><component-one></component-one><component-one /></div></template><script>import ComponentOne from './components/ComponentOne.vue'export default {components: { ComponentOne },}</script>
自闭合组件表示它们不仅没有内容,而且刻意没有内容。其不同之处就好像书上的一页白纸对比贴有“本页有意留白”标签的白纸。而且没有了额外的闭合标签,你的代码也更简洁。
不幸的是,HTML 并不支持自闭合的自定义元素——只有官方的“空”元素。所以上述策略仅适用于进入 DOM 之前 Vue 的模板编译器能够触达的地方,然后再产出符合 DOM 规范的 HTML。
