组件存在的意义就是解决软件开发过程中的复用问题。举个例子,在网页开发过程中,我们的网站很大概率上所有的页面都有相同的header,footer。因此我们只用写一遍header模块和footer模块,然后在其他页面中引用header模块和footer模块就OK。我们可以称header模块跟footer模块为组件。
VUE中定义组件的姿势如下:
var MyComponent = Vue.extend({......});
这样我们就获得了一个组件构造器。但是我们现在还无法使用这个组件,需要先对其进行注册,而注册组件的方式又分为全局注册与局部注册。
组件全局注册
全局注册需要确保在根实例初始化之前注册,这样才能使组件在任意实例中被使用
Vue.component('my-component', MyComponent);
这条语句需要写在 var vm = new Vue({…}) 之前,注册成功之后,就可以在模块中以自定义元素 <my-component> 的形式使用组件。对于组件的命名, W3C 规范是字母小写且包含一个短横杠“-”, Vue.js 暂不强制要求,但官方建议遵循这个规则比较好。
完整demo如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/vue.min.js"></script>
</head>
<body>
<div id="app">
<my-component></my-component>
</div>
</body>
<script>
//声明组件
var myComponent = Vue.extend({
template: '<p>This is a component</p>'
});
//注册全局组件
Vue.component('my-component', myComponent);
var vm = new Vue({
el: '#app'
});
</script>
</html>
组件局部注册
局部注册则限定了组件只能在被注册的组件中使用,而无法在其他组件中使用。
操作如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/vue.min.js"></script>
</head>
<body>
<div id="app">
<parent-component></parent-component>
</div>
</body>
<script>
//声明组件
var childComponent = Vue.extend({
template: '<h1>This is child component</h1>'
});
var parentComponent = Vue.extend({
template: '<div><p>This is parent component</p><child-component></child-component><div>',
//局部組件
components:{
'child-component':childComponent
}
});
//注册全局组件
Vue.component('parent-component', parentComponent);
var vm = new Vue({
el: '#app'
});
</script>
</html>
语法糖
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/vue.min.js"></script>
</head>
<body>
<div id="app">
<parent-component></parent-component>
</div>
</body>
<script>
//声明组件
var parentComponent = Vue.extend({
template: '<div><p>This is parent component</p><child-component></child-component><div>',
//局部組件
components:{
//语法糖,简写组件声明
'child-component':{
template: '<h1 style=\'color:red\'>This is child component</h1>'
}
}
});
//注册全局组件
Vue.component('parent-component', parentComponent);
var vm = new Vue({
el: '#app'
});
</script>
</html>
网友评论