vue组件笔记

组件

使用组件

  • 全局注册组件 标签名
    • Vue.component(‘my-component’,{
      template:’{{counter}}‘,
      data: function() { //组件中 data必须是函数
      return {counter:0}
      }
      });
  • 局部注册
    • var Child = {
      template: ‘
      A custom component!

      }
      new Vue({
      // …
      components: {
      // 将只在父模板可用
      ‘my-component’: Child
      }
      })
  • 对于一些默认包含的标签 可以这样使用模板


Prop 用于传递数据

  • 子模板获得父组件的数据

    • Vue.component(‘child’, {
      // 声明 props
      props: [‘myMessage’],
      // 就像 data 一样,prop 可以用在模板内
      // 同样也可以在 vm 实例中像 “this.message” 这样使用
      template: ‘{{ myMessage }}’
      })

      js组件中用驼峰命名 html中用短横分开
      动态绑定父组件数据

  • 传递参数要传递真正的number,需要用到v-bind 加了v-bind会将值解析为js表达式 从而传入的number,否则为number。
  • 将props传入的值进行修改
    • 定义一个局部变量
    • props: [‘initialCounter’],
      data: function () {
      return { counter: this.initialCounter }
      }
    • 定义一个计算属性
    • props: [‘size’],
      computed: {
      normalizedSize: function () {
      return this.size.trim().toLowerCase()
      }
      }

Props验证

Vue.component('example', {
  props: {
    // 基础类型检测 (`null` 意思是任何类型都可以)
    propA: Number,
    // 多种类型
    propB: [String, Number],
    // 必传且是字符串
    propC: {
      type: String,
      required: true
    },
    // 数字,有默认值
    propD: {
      type: Number,
      default: 100
    },
    // 数组/对象的默认值应当由一个工厂函数返回
    propE: {
      type: Object,
      default: function () {
        return { message: 'hello' }
      }
    },
    // 自定义验证函数 ? 有什么用
    propF: {
      validator: function (value) {
        return value > 10
      }
    }
  }
})

子元素传递数据到父组件

  • 组件监听事件$on(eventName)
  • 组件触发事件$emit(eventName)

    {{ total }}

    Vue.component(‘button-counter’, {
    template: ‘{{ counter }}‘,
    data: function () {
    return {
    counter: 0
    }
    },
    methods: {
    increment: function () {
    this.counter += 1
    this.$emit(‘increment’) //告诉父组件事件触发
    }
    },
    })
    new Vue({
    el: ‘#counter-event-example’,
    data: {
    total: 0
    },
    methods: {
    incrementTotal: function () {
    this.total += 1
    }
    }
    })

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值