如果data是对象,会影响其他组件的渲染
data是函数的话 会产生函数作用域,保证data只在当前组件起作用 , 可以保持函数返回的数据的私有性。不会被其他组件访问
1-组件的定义,使用继承。全局组件注册
let VueComponent=Vue.extend({ // 报错,data必须是函数 // 是函数的话 会产生函数作用域,保证data只在当前组件起作用 // data是函数的话可以保持函数返回的数据的私有性。不会被其他组件访问 data(){ return{ count:0 } }, // template:模板 模板字符串 template:`<div><h2>count:{{count}}</h2> <button @click="count++">count++</button> </div>` }) // 全局组件注册 ,第一个是组件的名称,第二个就是组件 Vue.component('MyButton',VueComponent)
2-组件的简写
// 组件的简写模式,内部实质上也调用了 Vue.extend ,然后返回子类构造器 Vue.component('MyButton',{ data(){ return { count:0 } }, template:`<div><h2>count:{{count}}</h2> <button @click="count++">count++</button> </div>` })
3-组件局部注册
let vm = new Vue({ el: '#app', // 全局都是双数 // 局部指令注册:directives // 局部过滤器注册:filters // 局部组件注册:components components: { myButton: { data() { return { count: 0 } }, template: `<div><h2>count:{{count}}</h2> <button @click="count++">count++</button> </div>` } } });
4-组件的使用
1-中划线:
<my-button></my-button>
2-大驼峰:
<MyButton></MyButton>
3-小驼峰:
<myButton></myButton>
整体代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>02.custom-component-extend</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 组件的调用 -->
<my-button></my-button>
<my-button></my-button>
</div>
<script type="text/javascript">
// TODO:利用extend定义组件,确认data为什么必须是函数类型
// Vue的本质其实就是class,就是类,所以可以实现类的继承
// 组件的定义
// let VueComponent=Vue.extend({
// // 报错,data必须是函数
// // 是函数的话 会产生函数作用域,保证data只在当前组件起作用
// // data是函数的话可以保持函数返回的数据的私有性。不会被其他组件访问
// data(){
// return{
// count:0
// }
// },
// // template:模板 模板字符串
// template:`<div><h2>count:{{count}}</h2> <button @click="count++">count++</button> </div>`
// })
// // 全局组件注册 ,第一个是组件的名称,第二个就是组件
// Vue.component('MyButton',VueComponent)
// 全局都是单数
// 全局指令注册:Vue.directive
// 全局过滤器注册:Vue.filter
// 全局组件注册:Vue.component
// 组件的简写模式,内部实质上也调用了 Vue.extend ,然后返回子类构造器
// Vue.component('MyButton',{
// data(){
// return {
// count:0
// }
// },
// template:`<div><h2>count:{{count}}</h2> <button @click="count++">count++</button> </div>`
// })
let vm = new Vue({
el: '#app',
// 全局都是双数
// 局部指令注册:directives
// 局部过滤器注册:filters
// 局部组件注册:components
components: {
myButton: {
data() {
return {
count: 0
}
},
template: `<div><h2>count:{{count}}</h2> <button @click="count++">count++</button> </div>`
}
}
});
</script>
</body>
</html>