
作者 | Jeskson
掘金 | https://juejin.im/user/5a16e1f3f265da43128096cb

学习组件化开发,首先掌握组件化的开发思想,组件的注册方式,组件间的数据交互方式,组件插槽的用法,vue调式工具的用法,组件的方式来实现业务逻辑功能。
组件化开发思想,组件注册,组件调式,组件间的数据交互,组件插槽
组件化规范,就是多的可能性重用
全局组件注册语法
Vue.component(组件名称, { data: 组件数据, template: 组件模板内容})
// 定义一个名为button-counter的新组件Vue.component('button-counter', { data: function() { return { count: 0 } }, template: '点击了{{count}}次})
组件的用法
<div id="app">
Vue.component('button-counter', { data: function() { return { count: 0 } }, template: '点击了{{count}}' methods: { handle: function(){ this.count += 2; } }})var vm = new Vue({ el: '#app', data: { }});
组件注册时
data必须是一个函数,组件模板内容必须是单个跟元素
template: `
"handle">点击{{count}}次
da
`,
组件命名方式
// 短橫线方式Vue.component('my-component',{/*...*/})// 驼峰方式Vue.component('MyComponent',{/*...*/}}
局部组件注册
var ComponentA = { /*...*/ }var ComponentB = { /*...*/ }var ComponentC = { /*...*/ }new Vue({ el: '#app', components: { 'component-a': ComponentA, 'component-b': ComponentB, 'component-c': ComponentC, }})
vue调式工具的用法
Make sure you are using Node 6+ and NPM 3+
Clone this repo
npm install (Or yarn install if you are using yarn as the package manager)
npm run bulid
Open Chrome extension page
Check 'developer mode'
Click "load unpacked extension", and choose shells/chrome.
Hacking
Clone this repo
npm install
npm run dev
A plain shell with a test app will be available at localhost: 8100.
调式工具的安装
第一步,克隆仓库,第二步,安装依赖包,第三步,构建,第四步,打开Chrome扩展页面,第五步,选中开发者模式,第六步,加载已解压的扩展,选择shells/chrome。
组件间数据交互
父组件向子组件传值
组件内部通过props接收传递过来的值
Vue.component('dada-item', { props: ['title'], // 用于接收父组件接收过来的数据 template: '
{{title}}
'})
父组件通过属性的方式将值传递给子组件
<dada-item title="来自父组件的数据">dada-item>// 静态<dada-item :title="title">dada-item>// 动态的进行属性的绑定
代码示例:
"来自父组件的值">//父组件向子组件传递值Vue.component('dada-item', { // 子组件接收父组件 // title属性 props: ['title'], data: function() { return { msg: '子组件的数据' } }, template: '
{{msg+ "..." + title}}
'});var vm = new Vue({ el: '#app', data: { pmsg: '父组件中内容', ptitle: '动态', }});
props属性名的规则
在props中使用驼峰的形式,则在模板中需要使用短橫线的形式
字符串形式的模板中没有这个限制
Vue.component('dada-item', { // 在JavaScript中驼峰式的 props: ['daTitle'], template: '
{{title}}
'})// 在html中是短横线方式的"dada">
id="app">
{{pmsg}}
"ptitle">
// 父组件向子组件传值-属性名
Vue.component('third-com', {
props: ['testTitle'],
template: '
{{testTitle}}
'
});
Vue.component('menu-item', {
props:['menuTitle'],
template: '
{{menuTitle}}
'
});
props属性值的类型
字符串类型 string
数值类型 number
布尔值类型 boolean
数组类型 array
对象 object
// 字符串形式
"app"> <div>{{pmsg}}div>
"pstr">menu-item>
div>