vue.js组件

有一篇非常棒的关于vue.js的组件的文章,写的特别好,特别清楚,容易理解。链接:上篇:http://www.cnblogs.com/keepfool/p/5625583.html 下篇:http://www.cnblogs.com/keepfool/p/5637834.html

以下是我学习链接所对应的这两篇文章的学习摘要。

1.组件的创建和注册

1.1 创建组件构造器(使用Vue.extend({模板}))

var child = Vue.extend({
    template:'
This is my first component!
' })

1.2 注册组件:Vue.component({'组件名',组件构造器名})

Vue.component('my-component',myComponent)

1.3 使用组件

new Vue({
    el:'#app'
});
//组件需挂载到对应的vue实例的挂载范围内

1.4 全局注册

eg:

渲染为:

A component!
效果图

1.5 局部注册

eg:

效果图

1.3 全局注册和局部注册区分

在new Vue ()中注册的为局部注册,只能挂到id值与new Vue()中的el值相同的Vue实例,而在new Vue外注册的为全局注册的,可以挂到各个Vue实例。
eg:

//将局部注册的组件挂到不对应的组件上,无法正确显示
无法正确显示两句话

eg:

//将全局注册的组件挂到不同id值的组件上
正确地显示了两行话

2.父组件和子组件

在一个组件的模板(template)中使用了其他组件,这两个组件之间就构成了父子关系,该组件是父组件,父组件的模板中的组件是子组件。

子组件只能在父组件的template中使用。

  • 创建父组件构造器
  • 创建子组件构造器
  • 注册父组件
  • 注册子组件
  • 使用组件
运行结果

3.组件注册语法糖:Vue.js简化组件注册的过程

3.1 使用Vue.component()直接创建和注册组件:

// 全局注册,my-component1是标签名称
Vue.component('my-component1',{
    template: '
This is the first component!
' }) var vm1 = new Vue({ el: '#app1' })

使用这种方式,Vue在背后会自动地调用Vue.extend()。

3.2 在选项对象的components属性中实现局部注册:

var vm2 = new Vue({
    el: '#app2',
    components: {
        // 局部注册,my-component2是标签名称
        'my-component2': {
            template: '
This is the second component!
' }, // 局部注册,my-component3是标签名称 'my-component3': { template: '
This is the third component!
' } } })

4. 使用script或template标签:分离js代码template中的HTML元素

4.1 使用标签中,而组件的template的值为

4.2 使用