组件系统是Vue.js其中一个重要的概念,它提供了一种抽象,让我们可以使用独立可复用的小组件来构建大型应用,任意类型的应用界面都可以抽象为一个组件树。

  那么什么是组件呢?组件可以扩展HTML元素,封装可重用的HTML代码,我们可以将组件看作自定义的HTML元素。

一、组件的创建和注册基本步骤

  Vue.js的组件的使用有3个步骤:创建组件构造器、注册组件和使用组件。

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 3. #app是Vue实例挂载的元素,应该在挂载元素范围内使用组件-->
<my-component></my-component>
</div>
<script>
// 1.创建一个组件构造器
var myComponent = Vue.extend({
template: '<h1>This is my first component!</h1>'
}) // 2.注册组件,并指定组件的标签,组件的HTML标签为<my-component>
Vue.component('my-component', myComponent) new Vue({
el: '#app'
}); </script>
</body>
</html>

  上面代码演示了这3个步骤:可以看到,使用组件和使用普通的HTML元素没什么区别。

二、理解组件的创建和注册

  我们用以下几个步骤来理解组件的创建和注册:

  1. Vue.extend()是Vue构造器的扩展,调用Vue.extend()创建的是一个组件构造器,而不是一个具体的组件实例。 
  2. Vue.extend()构造器有一个选项对象,选项对象的template属性用于定义组件要渲染的HTML。 
  3. 使用Vue.component()注册组件时,需要提供2个参数,第1个参数是组件的标签,第2个参数是组件构造器。 
  4. Vue.component()方法内部会调用组件构造器,创建一个组件实例。 
  5. 组件应该挂载到某个Vue实例下,否则它不会生效。

  请注意第5点,只有挂载到vue实例下组件才起到作用。

三、全局注册和局部注册

  调用Vue.component()注册组件时,组件的注册是全局的,这意味着该组件可以在任意Vue实例下使用。

  如果不需要全局注册,或者是让组件使用在其它组件内,可以用选项对象的components属性实现局部注册。

  局部组件注册方式:

// 1.创建一个组件构造器
var myComponent = Vue.extend({
template: '<div>This is my first component!</div>'
}) new Vue({
el: '#app',
components: {
// 2. 将myComponent组件注册到Vue实例下
'my-component' : myComponent
}
});

  注意:该局部组件只能在app下才能起作用

四、父组件和子组件

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

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 3. #app是Vue实例挂载的元素,应该在挂载元素范围内使用组件-->
<parent-component></parent-component>
</div>
<script>
// 1.创建一个组件构造器
// 子集
var child = Vue.extend({
template:"<h3>child component</h3>"
});
//父级
var parent = Vue.extend({
//在parent组件里使用child组件
template: '<div><h2>This is parent component!</h2><child-component></child-component></div>',
//在parent里面注册child组件,属于一种局部注册的方式
components:{
"child-component":child
}
});
// 2、全局注册parent组件
Vue.component("parent-component",parent); new Vue({
el: '#app'
});
</script>
</body>
</html>

  注意组件的模板只能有一个根元素。下面的情况是不允许的。

template: '<h2>This is parent component!</h2><child-component></child-component>',

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

  (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组件的内容也被渲染出来

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

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

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

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

//1. 以子标签的形式在父组件中使用
<div id="app">
<parent-component>
<child-component></child-component>
</parent-component>
</div>
//为什么这种方式无效呢?因为当子组件注册到父组件时,Vue.js会编译好父组件的模板,模板的内容已经决定了父组件将要渲染的HTML。
<parent-component>…</parent-component>相当于运行时,它的一些子标签只会被当作普通的HTML来执行,<child-component></child-component>不是标准的HTML标签,会被浏览器直接忽视掉。 //2. 在父组件标签外使用子组件
<div id="app">
<parent-component>
</parent-component>
<child-component>
</child-component>
</div>
//运行这段代码,浏览器会提示以下错误:Unknown custom element: <child-component> - did you register the component correctly?

五、组件注册语法糖

  以上组件注册的方式有些繁琐,Vue.js为了简化这个过程,提供了注册语法糖:相当于把Vue.extend()直接放入第二个参数

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

// 全局注册,my-component是标签名称,后面跟模板template
Vue.component('my-component',{
template: '<div>This is the first component!</div>'
})

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

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

var vm = new Vue({
el: '#app',
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模板分离出来。

  1、使用<script>标签

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
<div id="app">
<parent-component></parent-component>
</div>
<script type="text/x-template" id="template">
<div>this is a template!</div>
</script>
<script>
// 1.创建一个组件构造器
var parent = Vue.extend({
//在parent组件里使用child组件
template: '#template',
});
// 2、全局注册parent组件
Vue.component("parent-component",parent); new Vue({
el: '#app'
});
</script>
</body>
</html>

  template选项现在不再是HTML元素,而是一个id选择器,Vue.js根据这个id查找对应的元素,然后将这个元素内的HTML作为模板进行编译。

  注意:使用<script>标签时,type指定为text/x-template,意在告诉浏览器这不是一段js脚本,浏览器在解析HTML文档时会忽略<script>标签内定义的内容。

  2、使用<template>标签

  如果使用<template>标签,则不需要指定type属性。

    //template里面必须还得跟html标签,不能直接写text,否则浏览器会报错
<template id="template">
<div>this is a template!</div>
</template>

  在理解了组件的创建和注册过程后,我建议使用<script>或<template>标签来定义组件的HTML模板。这使得HTML代码和JavaScript代码是分离的,便于阅读和维护。

七、组件的el和data选项

  传入Vue构造器的多数选项也可以用在 Vue.extend() 或Vue.component()中,不过有两个特例: data 和el

  Vue.js规定:在定义组件的选项时,data和el选项必须使用函数。这是因为如果像Vue实例那样,传入一个对象,由于JS中对象类型的变量实际上保存的是对象的引用,所以当存在多个这样的组件时,会共享数据,导致一个组件中数据的改变会引起其他组件数据的改变。而使用一个返回对象的函数,每次使用组件都会创建一个新的对象,这样就不会出现共享数据的问题来了。

  下面的代码在执行时,浏览器会提出一个错误

Vue.component('my-component', {
data: {
a:
}
})

  如果data选项指向某个对象,这意味着所有的组件实例共用一个data。我们应当使用一个函数作为 data 选项,让这个函数返回一个新对象

Vue.component('my-component', {
data: function(){
return {a : }
}
})

八、父子组件通讯

  组件实例的作用域是孤立的。这意味着不能并且不应该在子组件的模板内直接引用父组件的数据。可以使用 props 把数据传给子组件

  1、props基础示例:

  下面4步

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
<div id="app">
//4、将父组件数据通过已定义好的props属性传递给子组件
<my-component v-bind:my-name="name" v-bind:my-age="age"></my-component>
</div>
//3、定义子组件的HTML模板
<template id="myComponent">
<table>
<tr><th colspan="">子组件数据</th></tr>
<tr><td>my name</td><td>{{ myName }}</td></tr>
<tr><td>my age</td><td>{{ myAge }}</td></tr>
</table>
</template>
<script>
var vm = new Vue({
el: '#app',
data: {
name: 'keepfool',
age:
},
//1、定义一个子组件my-component,在Vue实例中定义了data选项
components: {
'my-component': {
template: '#myComponent',
//为了便于理解,你可以将这个Vue实例看作my-component的父组件。
//2、如果我们想使用父组件的数据,则必须先在子组件中定义props属性,也就是props: ['myName', 'myAge']
props: ['myName', 'myAge']
}
}
})
</script>
</body>
</html>

  注意:在子组件中定义prop时,使用了camelCase命名法。由于HTML特性不区分大小写,camelCase的prop用于特性时,需要转为 kebab-case(短横线隔开)。例如,在prop中定义的myName,在用作特性时需要转换为my-name

  简单效果:

  父组件是如何将数据传给子组件的呢?相信看了下面这图,也许你就能很好地理解了。

  在父组件中使用子组件时,通过以下语法将数据传递给子组件:

<child-component v-bind:子组件prop="父组件数据属性"></child-component>

  2、prop的绑定类型:单向绑定

  既然父组件将数据传递给了子组件,那么如果子组件修改了数据,对父组件是否会有所影响呢?我们将子组件模板和页面HTML稍作更改:

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
<div id="app">
<table>
<tr><th colspan="">父组件数据</td></tr>
<tr><td>name</td><td>{{ name }}</td><td><input type="text" v-model="name" /></td></tr>
<tr><td>age</td><td>{{ age }}</td><td><input type="text" v-model="age" /></td></tr>
</table>
<my-component v-bind:my-name="name" v-bind:my-age="age"></my-component>
</div>
<template id="myComponent">
<table>
<tr><th colspan="">子组件数据</th></tr>
<tr><td>my name</td><td>{{ myName }}</td><td><input type="text" v-model="myName"></td></tr>
<tr><td>my age</td><td>{{ myAge }}</td><td><input type="text" v-model="myAge"></td></tr>
</table>
</template>
<script>
var vm = new Vue({
el: '#app',
data: {
name: 'keepfool',
age:
},
//1、定义一个子组件my-component,在Vue实例中定义了data选项
components: {
'my-component': {
template: '#myComponent',
//为了便于理解,你可以将这个Vue实例看作my-component的父组件。
//2、如果我们想使用父组件的数据,则必须先在子组件中定义props属性,也就是props: ['myName', 'myAge']
props: ['myName', 'myAge']
}
}
})
</script>
</body>
</html>

  测试验证结果:

  (1)在页面上修改子组件的数据,对父组件数据没有影响;

  (2)在页面上修改父组件的数据,同时子组件数据跟着改变。

  因此可见:prop默认是单向绑定:当父组件的属性变化时,将传导给子组件,但是反过来不会。这是为了防止子组件无意修改了父组件的状态。

  3、双向绑定

  可以使用.sync显式地指定双向绑定,这使得子组件的数据修改会回传给父组件。

<my-component v-bind:my-name.sync="name" v-bind:my-age.sync="age"></my-component>

  注意:只有vue1.0的可以,我使用的版本是vue.1.0.25

  4、示例

  为了尽快消化这些知识,我们来做一个小示例:可以直接拷贝查看效果

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app">
<div>
Search:<input type="text" v-model="searchQuery" />
</div>
<my-component v-bind:data="gridData" v-bind:columns="gridColumns" v-bind:filter-key="searchQuery"></my-component>
</div>
<template id="myComponent">
<table>
<th v-for="col in columns">{{col | capitalize}}</th>
<tr v-for="entry in data | filterBy filterKey">
<td v-for="val in entry">{{val}}</td>
</tr>
</table>
</template>
</body>
<script src="vue.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
searchQuery: '',
gridColumns: ["name","age","sex"],
gridData:[{
name: 'Jack',
age: ,
sex: 'Male'
}, {
name: 'Bill',
age: ,
sex: 'Male'
}, {
name: 'Tracy',
age: ,
sex: 'Female'
}, {
name: 'Chris',
age: ,
sex: 'Male'
}]
},
components: {
'my-component': {
template: '#myComponent',
props: {
data: Array,
columns: Array,
filterKey: String
}
}
}
})
</script>
</html>

search效果:

  除了以上介绍的知识点,这个示例还用到了两个知识点:

  5、 prop验证

props: {
data: Array,
columns: Array,
filterKey: String
}

  这段代码表示:父组件传递过来的data和columns必须是Array类型,filterKey必须是字符串类型。更多prop验证的介绍,请参考:官方文档prop验证

  6、filterBy过滤器

  可以根据指定的字符串过滤数据。

  注意:只有vue1.0才有这些默认的过滤器,vue2.0需要自己自定义过滤器

最新文章

  1. [No0000AB]用Visual Studio 2015在 WIN10 64bit 上编译7-zip (32 bit)
  2. Java Mysql连接池配置和案例分析--超时异常和处理
  3. etcd api 接口
  4. 【NOIP 2015 &amp; SDOI 2016 Round1 &amp; CTSC 2016 &amp; SDOI2016 Round2】游记
  5. QIBO /do/jf.php EvilCode Execution Injected By /hack/jfadmin/admin.php
  6. C风格字符串与C++风格字符串
  7. Spring事务解析2-标签解析
  8. java: cairo-misc.c:380: _cairo_operator_bounded_by_source: Assertion `NOT_REACHED&#39; failed.
  9. LeetCode Patching Array
  10. 深入理解C语言的函数调用过程
  11. 如何使用GitHub?
  12. apache2: bad user name ${APACHE_RUN_USER} 解决
  13. 【转】为什么C++编译器不能支持对模板的分离式编译
  14. C#线程总结
  15. spring jdbc.property的配置与使用
  16. IOS创建单例的两种方法
  17. java Io流中FileInputStream和BufferedInputStream的速度比较
  18. 笔记:Hibernate 拦截器和事件
  19. python3字典练习(重要)
  20. php 使用str_replace替换关键词(兼容字符串,一维数组,多维数组)

热门文章

  1. 记一次学习SpringBoot RequestBodyAdvice ResponseBodyAdvice RestControllerAdvice
  2. 【转】mybatis循环map的一些技巧
  3. linux tomcat 乱码
  4. PEP 3106 -- Revamping(改进) dict.keys(), .values() and .items()
  5. PYTHON设计模式学习(2):什么是设计模式
  6. ajaxfileupload异步上传文件
  7. (七)MySQL数据操作DQL:多表查询2
  8. MySql 分页关键字(limit)
  9. CF 862A Mahmoud and Ehab and the MEX【数组操作】
  10. Dijkstra【p4943】密室