学习笔记-vue2.x-组件

一. vue.js 组件

  • 组件化

  组件化:vue的一个重要概念,主张将庞杂的页面拆分成一个个小模块,每个模块实现独立的功能。

          vue组件即上述概念中的模块,使用独立复用的小组件来构建大型应用,几乎任意类型的应用的界面

                   都可以抽象为一个组件树

  组件:本质上是一个具有预定义选项的、可重复使用的vue实例,组件名是独一无二的。

  组件的作用:组件用于扩展HTML元素(作为自定义的HTML标签使用),封装可重用的代码。

  • 组件使用
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title>组件基础</title>
 6         <script src="../vue.js" type="text/javascript" charset="utf-8"></script>
 7     </head>
 8     <body>
 9         <div id='app' v-bind:title="message"> <!--绑定元素attribute-->
10             {{message}}                       <!--绑定DOM数据-->
11             <button-counter> <buttom-counter>
12         </div>
13         <script type="text/javascript">
14         <!--组件定义,data选项必须是函数-->
15             Vue.component('button-counter', {   
16                     data: function () {
17                     return {
18                             count: 0
19                         }
20                     },
21                 template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
22             })
23             var vm = new Vue({
24                 el: "#app",
25                 data:{
26                     message:"新组件:"
27                     }
28             });
29         </script>
30     </body>
31 </html>
View Code
  • 全局注册 和 局部注册

  为了能在模板中使用,组件必须先注册以便 Vue 能够识别。这里有两种组件的注册类型:全局注册和局部注册。

  全局注册:

    通过 Vue.component 全局注册

1 Vue.component('my-component-name', {
2   // ... 选项 ...
3 })
View Code

  局部注册:

    通过一个普通的 JavaScript 对象定义组件

1 var ComponentA = { /* ... */ }
2 var ComponentB = { /* ... */ }
View Code

    在components 选项中注册你想要使用的组件

1 new Vue({
2   el: '#app',
3   components: {
4     'component-a': ComponentA,
5     'component-b': ComponentB
6   }
7 })
View Code

 

二.父子组件

  在

三.传参机制

四.参考资料

       https://www.runoob.com/vue2/vue-component.html

  https://www.cnblogs.com/hellman/p/10985377.html

  https://cn.vuejs.org/v2/guide/components.html

  

new Vue({ el: '#components-demo' })

posted @ 2021-11-24 14:39  getright  阅读(29)  评论(0编辑  收藏  举报