您的位置:首页 > 其它

自定义组件(插件),指令,事件

2019-05-29 20:59 197 查看

1. 自定义组件( 插件 )

案例: 封装一个 Loading 组件
Loading是用来做什么的?
基于用户体验
loading使用方式很多

  1. 第三方的ui库/组件库
  2. 自定义封装 过程:
  3. 创建一个目录文件夹,称之为Loading
  4. 在loading中创建一个叫做component目录,用来放模板
  5. 在Loading目录下创建一个index.js
~ import Vue from 'vue'
import tpl from './component/index.html'
const Loading = {
// 自定义封装组件,这个loading对象中必须有一个关键key
install () {
Vue.component( 'Loading', {
template: tpl
})
}
}

export default Loading
  1. 使用:

2. 自定义指令

1. 指令是用来操作DOM
2. 指令的使用形式: 属性
3. 自定义指令方式有两种:
- 全局注册指令
Vue.directive( 指令的名称, 指令的配置项  )
- 局部注册指令
directives: {
'指令名称': 指令的配置项
}
研究:

指令的配置项提供了5个钩子函数

以及钩子函数中的参数
console.log( 'el',el  ) // el 指令绑定的元素
console.log( 'binding',binding ) // 指令的详细信息
console.log( 'vnode', vnode )  // 当前绑定元素的信息
console.log( 'oldVnode',oldVnode ) // 上一个绑定元素的信息

案例: 打开网页,input自动获得焦点
<body>
<div id="app">
<div class="box">
<button  @click = 'flag = false'> 点击 </button>
<input type="text"  v-if = "flag" v-focus.yyb v-model = "msg">
<input type="text"  v-if = "flag" v-focus v-model = "msg">
</div>
</div>
</body>
<script>
Vue.directive( 'focus',{
bind ( el,binding,vnode,oldVnode ) { //调用一次,指令一绑定在元素身上就会触发
// console.log( 'bind focus' )
// console.log( 'el',el  ) // el 指令绑定的元素
// console.log( 'binding',binding ) // 指令的详细信息
// console.log( 'vnode', vnode )  // 当前绑定元素的信息
// console.log( 'oldVnode',oldVnode ) // 上一个绑定元素的信息
// el.style.background = 'red'
},
inserted (  el,binding,vnode,oldVnode ) { // 当前绑定的元素插入父节点时调用
el.focus()
if( binding.modifiers.yyb ){
el.style.color = 'green'
}else{
el.style.color = 'red'
}
console.log( binding )
console.log( 'inserted ' )
},
update ( el, binding, vnode, oldVnode ) {  // 当前指令绑定的元素发生改变
console.log( 'update' )
console.log( 'el',el  ) // el 指令绑定的元素
console.log( 'binding',binding ) // 指令的详细信息
console.log( 'vnode', vnode )  // 当前绑定元素的信息
console.log( 'oldVnode',oldVnode ) // 上一个绑定元素的信息
},
componentUpdated ( el,binding,vnode,oldVnode) { //当前绑定元素发生改变,或是子元素发生改变
console.log( 'componentUpdated' )
},
unbind ( el,binding,vnode,oldVnode) { // 组件销毁时触发
console.log( 'unbind' )
}
})

new Vue({
el: '#app',
data: {
msg: 1000,
flag: true
<
1c140
span class="token punctuation">},
directives: {
'focus': {
bind () {

},
inserted () {

},
update () {

},
componentUpdated () {

},
unbind () {

}
}
}
})
</script>

3. 自定义的事件

v-on:click = ‘aa’
v-on:yyb = ‘aa’
v-on:before-enter: ‘’

  • 自定义封装组件的使用

  • 自定义事件的第二种使用形式
    事件的发布
    事件的订阅

    自定义事件的使用形式
    1. 组件生命周期中发布事件,通过某一个事件处理程序调用
    2. 绑定在组件身上 , 通过 v-on 绑定

<body>
<div id="app">
<button @click = 'fn'> 点击 </button>
</div>
</body>
<script>
var vm = new Vue({
el: '#app',
methods: {
fn () {
this.$emit('aa')
}
},
mounted () {
this.$on('aa',function(){
alert('aa')
})
}
})

</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: