组件
使用组件
- 全局注册组件 标签名
- Vue.component(‘my-component’,{
template:’{{counter}}‘,
data: function() { //组件中 data必须是函数
return {counter:0}
}
});
- Vue.component(‘my-component’,{
- 局部注册
- var Child = {
template: ‘A custom component!’
}
new Vue({
// …
components: {
// 将只在父模板可用
‘my-component’: Child
}
})
- var 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
}
}
})