全局组件注册
Vue.component('first-component', {
data: function () {
return {
count: 0
}
},
template: ''
})
data 必须是一个函数
组件模板内容必须是单个根元素
组件模板内容可以是模板字符串
全局组件可以嵌套全局组件
组件命名方式
Vue.component('first-component', {})
// 普通标签模板中不能使用驼峰, 只能在template中使用驼峰方式
Vue.component('firstComponent', {})
局部组件注册
局部注册的组件只能在父组件中使用 ;
var vm = new Vue({
components: {
'hello-world': {
data: function () {
return {
msg: 'hello world'
}
},
template: '{{ msg }}'
}
}
})
props 传递数据原则 : 单向数据流
组件内部通过 props 接收传递过来的值
Vue.component('son-com', {
props: ['msg', 'parentMsg']
template: '{{msg + "---" + parentMsg}}'
})
父组件通过属性将值传递给子组件
props 属性名规则
- 在props中使用驼峰形式, 模板中需要使用短横线的形式 ; html 对大小写的不敏感的
- 字符串中没有这个限制
props 传递类型
Vue.component('son-com', {
props: ['str', 'num', 'boolean', 'arr', 'obj'],
template: `
{{ str }}
{{ num }}
{{ boolean }}
- {{ item }}
var vm = new Vue({
el: '#app',
data: {
pstr: 'hello Vue',
pnum: 12,
pboolean: true,
parr: ['apple', 'banner', 'orange'],
pobj: {name: 'zs', age: 22}
}
})
子组件向父组件传值
子组件通过自定义事件向父组件传值 $emit()
Vue.component('son-com', {
template: `
传值从第二个参数开始
`
})
父组件监听子组件事件
父组件
var vm = new Vue({
el: '#app',
data: {
font: 10
},
methods: {
handle: function (val) {
this.font += 5
this.font += val // 此时的val就是 子组件传递过来的值
}
},
})
非父子组件传值
单独的事件中心管理组件之间的通信
// 创建事件中心
var hub = new Vue()
// 在 mounted 中监听事件
hub.$on('eventName', fn)
hub.$off('eventName') // 销毁事件
// 在 methods 中处理事件
hub.$emit('eventName', param)
组件插槽
程序错误
我是没有匹配的内容匹配页脚一次
匹配页脚两次
Vue.component('tmp-com', {
template: `
如果上面没有匹配到对应的标签就会展示默认内容
`
})
到此这篇关于Vue关于组件化开发知识点详解的文章就介绍到这了,更多相关Vue 组件化开发内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!



