vue--组件基础

组件是可复用的 vue 实例,它与new Vue 接收相同的参数,例如:data、methods、computed、watch 以及生命周期钩子。除了 el 等。

1、组件注册必须有一个组件名。

  组件名有两种命名方式:base-button 或者 BaseButton。

1、data 必须是一个函数。一个组件的data必须是一个函数。

2、组件注册有两种:局部注册、全局注册。

  全局注册:的组件可以用在其被注册之后的任何(通过 new Vue) 新创建的 Vue 根实例,也包括其组件树中的所有子组件的模板中。全局注册往往是不够理想的。

  比如,如果你使用一个像 webpack 这样的构建系统,全局注册所有的组件意味着即便你已经不再使用一个组件了,它仍然会被包含在你最终的构建结果中。这

  造成了用户下载的 JavaScript 的无谓的增加。

  局部注册:的组件在其子组件中不可用。

3、通过 props 向子组件传递数据。

  一个组件默认可以拥有任意数量的 props,任意值都可以传递给任何 prop。

 1     Vue.component('my-button', {
 2       template: `<button>{{text}}</button>`,
 3       props: ['title', 'author', 'isTruthiness', 'phone', 'list']
 4     })
 5     // props 还可以写成对象,并且都有指定的值类型
 6     Vue.component('my-button', {
 7       template: `<button>{{text}}</button>`,
 8       props: {
 9         title: String,
10         author: Object,
11         isTruthiness: Boolean,
12         phone: Number,
13         list: Array
14       }
15     })

  单向数据流,单向下行绑定。

  ① 如果子组件想要改变或者使用父组件传递的props最好是定义一个本地的data,然后将props作为初始值赋值给它。

1       props: ['initcounter'],
2       data: function() {
3         return {
4           counter: this.initcounter
5         }
6       }

  ②这个props以原始值传入,并且需要进行转换,此时最好用这个prop定义一个计算属性。

1       props: ['numberlist'],
2       computed: {
3         targetlist: function() {
4           return this.numberlist.sort().reverse();
5         }
6       }

  ③ props 验证,这在一个可能会被别人用到的组件中是非常有用的。

 1     Vue.component('my-component', {
 2       props: {
 3         propA: String,
 4         porpB: [String, Number],
 5         propC: {
 6           type: String,
 7           required: true
 8         },
 9         propD: {
10           type: Number,
11           default: 100
12         },
13         propE: {
14           type: Object,
15           default: function() {
16             return { message: 'world peace' }
17           }
18         },
19         propF: {
20           // 自定义校验方法
21           validator: function(value) {
22             return ['success', 'fail', 'complete'].indexOf(value) !== -1;
23           }
24         }
25       }
26     })

4、每个组件只能有一个根元素。

5、通过事件向父级组件发送消息。

  通过 $emit(eventName, params) 向父级发送事件,父级通过 v-on 监听事件来执行。在父级可以通过 $event 来访问被抛出的参数。

6、is="componentA"  就是把这个标签当做这个组件componentA 。解析DOM模板时注意事项。

原文地址:https://www.cnblogs.com/xguoz/p/10225048.html