组件化开发
组件化开发思想
组件化规范:Web Components
- 尽可能多的重用代码
- 自定义组件的方式不太容易(html、css和js)
- 多次使用组件可能导致冲突
通过创建封装好功能的定制元素解决
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NA1ZN2RY-1617027150596)(F:\笔记\Vue基础\image-20210126110142299.png)]
组件注册
Vue.component(组件名称, {
data: 组件数据,
template: 组件模板内容
})
组件注册注意事项
-
data必须是一个函数
-
分析函数与普通对象的对比
使用函数的形式可以形成一个闭包的环境,每个组件都拥有一个独立的数据
-
-
组件模板内容必须是单个根元素
-
组件模板内容可以是模板字符串
template:``
-
组件命名方式
-
短横线方式
-
Vue.component('my-component', {})
-
-
驼峰方式
-
Vue.component('MyComponent', {})
-
-
如果使用驼峰式命名组件,那么在使用组件的时候,只能在字符串模板中用驼峰的方式使用组件,但是在普通的标签模板中,必须使用短横线的方式使用组件
局部组件注册
new Vue({
el: '#app',
data: {},
components: {
'component-a' : ComponentA
}
})
局部注册的组件只能在注册它的父组件中使用
组件间数据交互
父组件向子组件传值
-
子组件内部通过props接收传递过来的值
-
Vue.component('menu-item', { props: {'title'}, template: '<div>{ {title}}</div>' })
-
-
父组件通过属性将值传递给子组件
-
<menu-item title="来自父组件的数据"></menu-item> <menu-item :title="title"></menu-item>
-
<div id="app"> <component-a ></component-a> </div> <script> Vue.component('componentA', { data: function(){ return { father: "我是父组件过来的" } }, template: '<div>父组件<component-b :father="father"></component-b></div>', }); Vue
-