一、directives自定义指令
自定义指令提供一种机制将数据的变化映射为 DOM 行为。
可以用 Vue.directive(id, definition) 方法注册一个全局自定义指令,它接收两个参数指令 ID 与定义对象。也可以用组件的 directives 选项注册一个局部自定义指令。
自定义指令的钩子函数
定义对象可以提供几个钩子函数(都是可选的):
bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
update: 在 bind 之后立即以初始值为参数第一次调用,之后每当绑定值变化时调用,参数为新值与旧值。
unbind:只调用一次,在指令从元素上解绑时调用。
inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
componentUpdated: 被绑定元素所在模板的所有子组件更新时调用。
Vue.directive('my-directive', {bind: function () {// 准备工作// 例如,添加事件处理器或只需要运行一次的高耗任务},update: function (newValue, oldValue) {// 值更新时的工作// 也会以初始值为参数调用一次},unbind: function () {// 清理工作// 例如,删除 bind() 添加的事件监听器}
})
举例一-dom颜色设置:
在如下这个例子中,我们创建了一个名为 v-color 的指令,可以通过传递参数来改变文本颜色。
// 注册自定义指令 v-color
Vue.directive('color', {bind(el, binding) {el.style.color = binding.value; // 从指令值中获取颜色}
});// 在 Vue 实例中使用指令
new Vue({el: '#app',template: `<div v-color="'blue'">This is blue text.</div>`
})
举例二-面包屑设置:
我们想要将每个页面的面包屑设置为当前选中的菜单项的名称,而不是固定将各个页面的面包屑名称分别写在各个页面内。
那么我们可以通过v-breadcrumb的directives 控制面包屑名称显示,同时为了避免重复代码,我们使用mixin。实现如下:
(function(){let Utils = {};let mixinDirective = {directives:{breadcrumb:{inserted(el){//PLAT_menu 存储当前选中菜单项的名称let val = sessionStorage.getItem('PLAT_menu');let firstChild = el.firstElementChild;if(firstChild){firstChild.innerText = val;}else{el.innerText = val;}}}}}Utils.mixinDirective = mixinDirective;
})
index.js
const user = new Vue({mixins:[Utils.mixinDirective]
})
index.html
<p-pageheader v-breadcrumb></p-pageheader>
举例三-v-auth实现权限控制
如下,根据权限控制新增按钮是否显示。
const dataForward = new Vue({directives:{auth:{bind:function(el,bind){el.originDisplay = el.style.display;if(!window.authObject || !bind || bind.value === undefined){return;}if(!window.authObject[bind.value]){el.style.display = 'none'}},update:function(el,bind){if(bind.value !== undefined && !window.authObject[bind.value]){el.style.display = 'none';} else{el.style.display = el.originDisplay;}}
<Button v-auth="10934">增加</Button>window.authObject = {10934:1}
二、虚拟滚动列表插件库vxe-table
站内信消息列表数据最多可达1000条数据,数据加载过多,前端页面卡顿。我们可以使用虚拟滚动列表库进行优化。
let internal_message = {template:`<vxe-list :data="notifyList" :height="treeHeight"><template v-slot="{ items }"><notifyCard v-for="(item,index) in items" :key="item.id" :item="item" :index="index" /></template></vxe-list>`,components:{vxeList:VXETable.List}}