(三)vue 组件

import Vue from 'vue'

// 定义一个新组件,组件是一个对象
const newComponent = {
  // 除了实例以外,组件的data必须是函数,作用是每个组件形成自己的作用域,避免变量互相影响
  data () {
    return {
      text: 11
    }
  },
  // 模版
  template: `<div>{{ text }} -- {{ school }}</div>`,
  // 接受来自父组件的参数
  props: {
    school: {
      type: String,
      default: ''
    }
  }
}

new Vue({
  el: '#app',
  components: { 
    newComponent
  },
  template: '<newComponent :school="school"/>',
  // 实例的data可以是一个对象
  data: {
    school: '东北学校'
  }
})

页面展示:

注意:

(1)props 的类型校验,如果类型不正确,依然页面显示正常,只不过浏览器 console 会报错,比如 school 赋值为 true (Boolean) 字段,页面依然会照常显示,浏览器报错

(2)如果props 传过来的是一个对象,指定对象的默认值,也要用函数

props: {
    school: {
      type: Object,
      // 注意对象的默认值
      default () {
        return {
          name: String
        }
      }
    }
  }

(3)组件的继承:两种方式

方法一:

import Vue from 'vue'

// 定义一个新组件,组件是一个对象
const newComponent = {
  data () {
    return {
      text: 11,
      school: {
        name: '东北大学'
      }
    }
  },
  template: `<div>{{ text }} -- {{ school.name }}</div>`,
  mounted () {
    console.log('newComponent mounted')
  }
}

// extendComponent 这个组件 Vue.extend 继承 newComponent
const extendComponent = Vue.extend(newComponent)

// 创建 extendComponent 实例
new extendComponent({
  el: '#app',
  // 覆盖 newComponent 的 data
  data: {
    text: 12,
    school: {
      name: '东北学'
    }
  },
  // 覆盖原来的props
  propsData: {
    xx: 'xx'
  },
  mounted () {
    console.log('new extendComponent mounted')
  }
})

方法一继承:

1. 使用 Vue.extend 指令,然后 new 新的 extend

2. 覆盖原来的props 要使用 propsData

3. 生命周期,先执行 基本的,再执行 继承的

方法二继承:注意是 extends 有s

import Vue from 'vue'

// 定义一个新组件,组件是一个对象
const newComponent = {
  data () {
    return {
      text: 11,
      school: {
        name: '东北大学'
      }
    }
  },
  template: `<div>{{ text }} -- {{ school.name }}</div>`,
  mounted () {
    console.log('newComponent mounted')
  },
  created () {
    console.log('newComponent created')
  }
}

// 使用extends 继承
const extendComponent = {
  extends: newComponent, // 继承
  // 覆盖 data
  data () {
    return {
      text: 12,
      school: {
        name: '东大学'
      }
    }
  },
  mounted () {
    console.log('extendComponent mounted')
  },
  created () {
    console.log('extendComponent created')
  }
}

new Vue({
  el: '#app',
  components: {
    extendComponent
  },
  template: '<extendComponent />'
})

生命周期,先执行 基本的,再执行 继承的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值