60分钟组件快速入门(上篇)(2)

60分钟组件快速入门(上篇)

父组件和子组件

我们可以在组件中定义并使用其他组件,这就构成了父子组件的关系。

<!DOCTYPE html> <html> <body> <div> <parent-component> </parent-component> </div> </body> <script src="https://www.jb51.net/js/vue.js"></script> <script> var Child = Vue.extend({ template: '<p>This is a child component!</p>' }) var Parent = Vue.extend({ // 在Parent组件内使用<child-component>标签 template :'<p>This is a Parent component</p><child-component></child-component>', components: { // 局部注册Child组件,该组件只能在Parent组件内使用 'child-component': Child } }) // 全局注册Parent组件 Vue.component('parent-component', Parent) new Vue({ el: '#app' }) </script> </html>

这段代码的运行结果如下:

60分钟组件快速入门(上篇)

我们分几个步骤来理解这段代码:

1.var Child = Vue.extend(...)定义一了个Child组件构造器

2.var Parent = Vue.extend(...)定义一个Parent组件构造器

3.components: { 'child-component': Child },将Child组件注册到Parent组件,并将Child组件的标签设置为child-component。

4.template :'<p>This is a Parent component</p><child-component></child-component>',在Parent组件内以标签的形式使用Child组件。

5.Vue.component('parent-component', Parent) 全局注册Parent组件

6.在页面中使用<parent-component>标签渲染Parent组件的内容,同时Child组件的内容也被渲染出来

60分钟组件快速入门(上篇)

Child组件是在Parent组件中注册的,它只能在Parent组件中使用,确切地说:子组件只能在父组件的template中使用。

请注意下面两种子组件的使用方式是错误的:

1. 以子标签的形式在父组件中使用

<div> <parent-component> <child-component></child-component> </parent-component> </div>

为什么这种方式无效呢?因为当子组件注册到父组件时,Vue.js会编译好父组件的模板,模板的内容已经决定了父组件将要渲染的HTML。

<parent-component>…</parent-component>相当于运行时,它的一些子标签只会被当作普通的HTML来执行,<child-component></child-component>不是标准的HTML标签,会被浏览器直接忽视掉。

2. 在父组件标签外使用子组件

<div> <parent-component> </parent-component> <child-component> </child-component> </div>

运行这段代码,浏览器会提示以下错误

60分钟组件快速入门(上篇)

组件注册语法糖

以上组件注册的方式有些繁琐,Vue.js为了简化这个过程,提供了注册语法糖。

使用Vue.component()直接创建和注册组件:

// 全局注册,my-component1是标签名称 Vue.component('my-component1',{ template: '<div>This is the first component!</div>' }) var vm1 = new Vue({ el: '#app1' })

Vue.component()的第1个参数是标签名称,第2个参数是一个选项对象,使用选项对象的template属性定义组件模板。
使用这种方式,Vue在背后会自动地调用Vue.extend()。

在选项对象的components属性中实现局部注册:

var vm2 = new Vue({ el: '#app2', components: { // 局部注册,my-component2是标签名称 'my-component2': { template: '<div>This is the second component!</div>' }, // 局部注册,my-component3是标签名称 'my-component3': { template: '<div>This is the third component!</div>' } } })

使用script或template标签

尽管语法糖简化了组件注册,但在template选项中拼接HTML元素比较麻烦,这也导致了HTML和JavaScript的高耦合性。
庆幸的是,Vue.js提供了两种方式将定义在JavaScript中的HTML模板分离出来。

使用<script>标签

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwfpfs.html