局部组件
一 概念
```html
<div id="app">
<local-tag></local-tag>
<local-tag></local-tag>
</div>
<script>
var localTag = {
data () {
return {
count: 0
}
},
template: '<button @click="btnAction">局部{{ count }}</button>',
methods: {
btnAction () {
this.count ++
}
}
}
new Vue({
el: "#app",
components: {
'local-tag': localTag
}
})
</script>
```
二 代码示范
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>局部组件</title>
<style type="text/css">
.sup {
width: 100px;
height: 100px;
background-color: orange;
}
.sub {
width: 100px;
height: 100px;
background-color: red;
border-radius: 50%
}
</style>
</head>
<body>
<div id="app">
<!-- 错误: html不区分大小写 -->
<!-- <localTag></localTag> -->
<!-- html中组件命名提倡-的链接语法 -->
<!-- <local-tag></local-tag> -->
<!-- 1 -->
<!-- <localtag></localtag>
<localtag></localtag>
<localtag></localtag> -->
<!-- 2 3 4 5 -->
<local-tag></local-tag>
<btn-tag></btn-tag>
<btn-tag></btn-tag>
</div>
</body>
<script src="js/vue-2.5.17.js"></script>
<script type="text/javascript">
// 如何定义一个局部组件
// 局部组件的语法规则
// 如何使用局部组件
// 为什么要使用局部组件(达到html+css+js代码块的复用)
// 一个满足vue语法规则的对象就是一个组件
// 直接来定义这样的组件,用一个变量名来接收,就是创建了一个局部组件,
// 变量名就是局部组件的组件名
// 通过组件名就可以使用该组件
// 局部组件要在父组件中使用,一定要提前在父组件中进行注册
// 语法规则
// 有自身模板template,有data/methods/computed/watch...
var localTag = {
template: "<div class='sup'><div class='sub'></div></div>"
}
var btnTag = {
// template: "<div><button>按钮1</button><button>按钮2</button></div>"
template: "<button @click='btnAction'>点击了{{ num }}下</button>",
// data需要绑定方法,数据通过方法返回值进行处理,达到组件复用时,数据的私有化
data: function() {
return {
num: 0
}
},
methods: {
btnAction: function () {
this.num++
}
}
}
// 根组件
new Vue({
el: "#app",
// 注册子组件
components: {
// 1
// "localtag": localTag
// 2
// "localTag": localTag
// 3
// "local-tag": localTag
// 4
// localTag: localTag
// 5 ES6对象语法,key value写法相同,可以省略value
localTag,
btnTag,
}
})
</script>
</html>