①. 组件化思想
- ①. 所谓组件化,就是把页面拆分成多个组件,每个组件自己管理所依赖的 CSS、JS、模板、图片等资源
- ②. 组件与组件之间通过特定的规则进行数据传递、就会行成树状结构
②. 全局注册
- ①. Vue.component(‘组件名称’, { }) 第1个参数是标签名称,第2个参数是一个选项对象
- ②. 注意事项:
data必须是一个函数
组件模板必须是单个根元素(下面这个是错误的,没有根元素)
组件模板的内容可以是模板字符串
③. 组件命名规则
如果使用驼峰式命名组件,那么在使用组件的时候,只能在字符串模板中用驼峰的方式使用组件
但是在普通的标签模板中,必须使用短横线的方式使用组件
④. 案列演示
<body> <div id="app"> <!--你可以将组件进行任意次数的复用:因为data中返回的是一个对象所以每个组件中的数据是私有的--> <button-count></button-count> <button-count></button-count> <!--必须使用短横线的方式使用组件--> <button-count></button-count> </div> <script src="../js/vue.js"></script> <script> Vue.component('button-count',{ //1. data必须是一个函数 data:function(){ return{ count:0 } }, //2. 组件模板必须是单个根元素(下面这个是错误的,没有根元素) //template:'<button @click="handle()">已经点击了{{count}}次了</button><button></button>', //3. 组件模板的内容可以是模板字符串 //template:'<button @click="handle()">已经点击了{{count}}次了</button>', template:` <button @click="handle()">已经点击了{{count}}次了</button> `, methods:{ handle(){ this.count+=2 } } }); var vm=new Vue({ el:'#app', data:{ } }); </script> </body> </html>