1 . 指令 – 用来操作 dom
2 . 组件 – 组件是 html css js的聚合体
为什么要使用组件?
要想使用组件化,那么这个组件是完整的
组件中的根元素必须是唯一
组件要先注册,再实例化,要在实例范围内执行
vue 借鉴 react ,组件以标签的形式呈现的。
//组件使用前必须先注册
Vue.component(组件名称,组件配置)
var Hello = Vue.extend({})
Vue.compoent('Father', Hello)
可以简化
Vue.componet('Father', {
template
})
组件的创建
全局注册
所有实例都可以使用
Vue.componet('Father', {
template
})
局部注册
在实例中间使用 components:{ }
new Vue({
el: '#app',
components: {
'Father': {
template: '局部组粗'
}
}
})
组件的嵌套
在父组件里放子组件: 将子组件以标签的形式放在父组件中
全局嵌套
这里是父组件模板
Vue.component('Father',{
template: '#father'
})
Vue.component('Son', {
template:' son '
})
局部嵌套
new Vue([
el: '#app',
compoents: {
template: ' father 组件 ',
components: {
'Son': {
template: ' son 组件
}
}
}
])
is 规则
ul>li ol>li table>tr>td select>option
如上直属父子级如果直接组件以标签化形式使用,会出现 bug
解决:需要通过 is 属性来绑定一个组件
组件的一些特殊使用规则 【
使用 props 来实现
//1.在父组件的模板中将数据用单项数据绑定的形式(v-bind)绑定到子组件上
<Son :aa = "money" :maskFlag = "maskFlag"/>
Vue.component('Father',{
template: '#father',
data () {
return {
money: 2000,
}
}
})
Vue.component('Son',{
template: '#son',
props: ['aa','maskFlag']
})
使用做自定义事件通信
在父组件模板中,通过事件绑定的形式,绑定一个自定义事件在子组件身上
//注意: fn 是在父组件配置项 methods 中定义
在子组件的配置项 methods 中写一个事件处理程序,在事件处理程序中 使用 $emit() 触发父组件中绑定的自定义事件
Vue.component('Son',{
template: '#son',
props: ['aa','maskFlag']
})
将子组件定义事件处理函数 ,绑定到子组件的按钮上
父组件通过 ref 链得到一个子组件的数据,在把数据发送到另一个子组件上,就可以实现非父子组件的通信,当是如果层级太多,就比较繁琐
通过 bus. o n 来 定 义 事 件 , 通 过 on 来定义事件,通过 on来定义事件,通过emit 来触发事件
在其中一个组件的 mounted 钩子函数上进行事件声明
Vue.component('sma', {
template: '#sma',
data() {
return {
flag: false
}
},
mounted () { //在 mounted 钩子函中事件声明
let _this = this
bus.$on('aa', function(){ // 事件声明
_this.flag = true;
})
}
})
在另一个组件中,通过 bus.$emit(‘aa’) 来触发这个事件
vuex
不推荐:因为 mvvm 框架是单项数据流
父组件窗体一个 对象类型 给子组件,子组件通过 props 接收,
会发现:子组件修改数据时,父组件的数据也会发生改变
因为父组件传递给子组件的是一个对象引用地址
这是fatcher 组件
父组件小金库 ---{{ xiaojingku.money }}
这是 son组件
son : {{ xiaojingku.money}}