组件注册以及其命名方式(规范):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>组件的注册和使用方式</title>
</head>
<body>
<div id="app">
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
<!-- <HelloWorld></HelloWorld> 此时命名方式在此组件中会报错~! -->
<hello-world></hello-world>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
// Vue.component('button-counter',{
// // 这里的 data 必须是函数 不能是对象。
// data: function(){
// return{
// count: 0
// }
// },
// //这里的 组件模板的 内容 必须是 单个跟元素 若必须加其它的 内容的话 ,得添加div
// template: '<div><button @click="handle">点击了{{count}}次</button><button>test</button></div>',
// methods: {
// handle: function(){
// // count++;
// this.count += 2;
// }
// }
// })
// -----------------------------------------------------------------------------------------------
/*
组件注册 注意事项
如果使用驼峰式命名组件,那么在使用组件的时候,只能在字符串模板中用驼峰的方式使用组件 ,
但是在普通的标签模板中,必须使用短横线的方式使用组件----> <hello-world></hello-world>。
*/
Vue.component('HelloWorld',{
data: function(){
return{
msg: 'HelloWorld'
}
},
template: '<div>{{msg}}</div>'
});
// 基于上述添加多个内容加<div>方法 麻烦的基础上,这里有可读性强的方法 如下:
Vue.component('button-counter', {
//这里的 data 必须是函数 不能是对象。
//组件数据
data: function() {
return {
count: 0
}
},
// 模板内容可以是模板字符串格式,支持(ES6)语法
template: `
<div>
<button @click="handle">点击了{{count}}次</button>
<button>test</button>
<HelloWorld></HelloWorld>
</div>
`,
// 模板内容
methods: {
handle: function(){
// count++;
this.count += 2;
}
}
});
var vm = new Vue({
el: '#app',
data: {
}
})
</script>
</body>
</html>
局部组件注册:
image.png
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- 父组件模板 -->
<div id="app">
<hello-world></hello-world>
<hello-tom></hello-tom>
<hello-jerry></hello-jerry>
<test-com></test-com>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
/*
局部组件注册:
局部组件只能在注册他的父组件中使用
*/
Vue.component('test-com',{
template: '<div>Test</div>',
// 下面句法错误 , 原因如上 注释。
// template: '<div>Test<hello-world></hello-world></div>'
})
var HelloWorld = {
data: function(){
return{
msg: 'HelloWorld'
}
},
template: '<div>{{msg}}</div>'
};
var HelloTom = {
data: function(){
return{
msg: 'HelloTom'
}
},
template: '<div>{{msg}}</div>'
};
var HelloJerry = {
data: function(){
return{
msg: 'HelloJerry'
}
},
template: '<div>{{msg}}</div>'
};
var vm = new Vue({
el: '#app',
data: {
},
components: {
'hello-world': HelloWorld,
'hello-tom': HelloTom,
'hello-jerry': HelloJerry,
}
});
</script>
</body>
</html>