1,自定义指令
自定义指令分:全局自定义指令和局部自定义指令。
1.1,全局自定义指令
Vue.directive
全局注册一个自定义指令:
1参:指令名字,
2参:指令的配置对象。
//main.js
// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el) {
// 聚焦元素
el.focus()
}
})
使用
<input v-focus>
1.2,局部自定义指令
在组件中,使用directives
定义局部自定义指令。
data() {
return {
}
},
directives: {
focus: {
// 指令的定义
inserted: function (el) {
el.focus()
}
}
},
created() {
},
2,自定义事件
自定义事件:一种组件间的通信方式,适用于子组件==>父组件。
- 在子组件中,使用
this.$emit
发射事件,可携带参数。
//不传参,只触发父组件对应的函数
// this.$emit('first-custom-event')
// 传参
this.$emit('first-custom-event', this.manObj.name, this.manObj.age, this.manObj.car)
- 在父组件中,给子组件添加自定义事件,事件名字和发射事件时保持一致。
<div>
<child @first-custom-event="handleAcceptData"></child>
<p>接收子组件传的数据:{{ childValue }}</p>
</div>
- 解绑事件
// 解绑1个事件
this.$off('first-custom-event');
// 解绑2个事件
this.$off('first-custom-event', '第二个事件名字');
// 全部解绑
this.$off();
2.1,完整代码
父组件代码
<template>
<div>
<h3>自定义事件</h3>
<div>
<!-- 2,在父组件中,给子组件添加自定义事件,事件名字在子组件中,发射事件时定义 -->
<child @first-custom-event="handleAcceptData"></child>
<p>接收子组件传的数据:{{ childValue }}</p>
</div>
</div>
</template>
<script>
import Child from './child.vue';
export default {
name: 'vueCustomEvent',
components: {
Child,
},
data() {
return {
childValue:'',
}
},
methods: {
handleAcceptData(data, ...params) {
console.log('数据接收成功')
this.childValue = data;
//如果接收多个值,可以用es6的...params
console.log(...params)
},
},
}
</script>
子组件代码
<template>
<div class="main">
<h3>子组件</h3>
<el-button type="primary" @click="handleSendData">向父组件发送数据</el-button>
<!-- 在子组件中,定义解绑事件 -->
<el-button type="danger" @click="handleUnbind">解绑自定义事件</el-button>
</div>
</template>
<script>
export default {
name: 'vueCustomEventChild',
data() {
return {
manObj:{
name: 'king',
age: 24,
sex: 1,
car:'红旗H9',
}
}
},
methods: {
handleSendData() {
console.log('数据发送成功,111')
//1,在子组件中,使用this.$emit发射事件,可携带参数
//不传参,只触发父组件对应的函数
// this.$emit('first-custom-event')
// 传参
this.$emit('first-custom-event', this.manObj.name, this.manObj.age, this.manObj.car,)
},
handleUnbind() {
console.log('事件解绑');
// 解绑1个事件
this.$off('first-custom-event');
// 解绑2个事件
this.$off('first-custom-event', '第二个事件名字');
// 全部解绑
this.$off();
}
},
}
</script>
<style scoped>
.main {
width: 200px;
background-color: rgb(0, 255, 153);
/* border: 2px solid rgb(81, 0, 255); */
}
</style>