1.新建format-time.js文件
import dtime from "time-formater";
function formatTime(app) {
app.directive("format-time", {
created(el, bindings) {
bindings.formatString =bindings.formatString?? "YYYY-MM-DD HH:mm:ss";
if (bindings.value) {
bindings.formatString = bindings.value;
}
},
mounted(el, bindings) {
const textContent = el.textContent;
el.textContent = dtime(textContent).format(bindings.formatString);
}
})
}
export default formatTime
2.然后在main.js中引入formatTime函数
const app=createApp(App)
app.use(router)
app.use(store)
formatTime(app) //重点在这里
app.mount('#app')
3.在vue文件中使用
<span v-format-time="YYYY-MM-DD">{{ scope.row.registe_time }}</span>
4.出现的问题
1.YYYY-MM-DD被识别成变量了,需要加上''
<span v-format-time="YYYY-MM-DD">{{ scope.row.registe_time }}</span>
2.因为我是将表格中的注册时间格式化,但是当我切换到下一页时,这个时间还是原来第一页的时间,并且也没有重新执行自定义指令的created和mounted,但是会执行updated
而且el.textContent始终是第一次的内容,无法获取到最新的
于是我将变化的日期作为参数传入自定义指令中,通过最新的value来给el.textContent赋值
import dtime from "time-formater";
function formatTime(app) {
app.directive("format-time", {
mounted(el,bindings){
const {format,time}=bindings.value;
el.textContent = dtime(time).format(format);
},
updated(el, bindings) {
if(bindings.value.time===bindings.oldValue.time){return}
const {format,time}=bindings.value;
el.textContent = dtime(time).format(format);
},
})
}
export default formatTime
使用:<span v-format-time="{format:'YYYY-MM-DD',time:scope.row.registe_time}"></span>
5.自定义指令字段说明
自定义指令可以接收三个参数
1. el:指令所绑定的元素,可以用来直接操作 DOM。
2. binding:一个对象,包含以下属性:
name:指令名,不包括 v- 前缀。
value:指令的绑定值,例如:v-my-directive="1 + 1" 中,绑定值为 2。
oldValue:指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
expression:字符串形式的指令表达式。例如 v-my-directive="1 + 1" 中,表达式为 "1 + 1"。
arg:传给指令的参数,可选。例如 v-my-directive:foo 中,参数为 "foo"。
modifiers:一个包含修饰符的对象。例如:v-my-directive.foo.bar 中,修饰符对象为 { foo: true, bar: true }。
3. vnode:Vue 编译生成的虚拟节点