Vue高级语法-自定义指令的参数修饰符以及案例

40 阅读1分钟

Vue高级语法-自定义指令的参数修饰符以及案例

<template>
  <div class="app">
    <h2 v-mjy:kobe.abc.cba="message">哈哈哈</h2>
  </div>
</template>
<script setup>
  const message= "你好,世界"
const vMjy = {
  mounted(el,bindings){
    //bandings 可以拿到所有的修饰符
    console.log(bindings)
    el.textContent = bindings.value
  }
}
​

运行结果

image-20231224182451110

通过修饰符将数据绑定到对应组件上

案例-数字添加人民币符号

需求: 在价格的前面加上人民币符号

代码:

<template>
  <div class="app">
        <h2 v-unit>{{ 111 }}</h2>
  </div>
</template>

directive文件夹下面新增一个unit.js

export default function directiveUnit(app) {
    app.directive("unit", {
        mounted(el, bindings) {
            const defaultText = el.textContent
            let unit = bindings.value
            if (!unit) {
                unit = "¥"
            }
            el.textContent = unit + defaultText
        }
    })
}

运行结果

image-20231224183207913

只需要在需要的文字前面输入v-unit即可添加人民币符号

案例2-日期格式化

<template>
  <div class="app">
    <h2 v-ftime>{{ timestamp }}</h2>
    <h2 v-ftime="'YYYY-MM-DD'">{{ timestamp }}</h2>
  </div>
</template>
<script setup>
const timestamp = 1231355453
</script>

在directive文件夹新增ftime.js

import dayjs from "dayjs"
export default function directiveFtime(app) {
    app.directive("ftime", {
        mounted(el,bindings) {
            //获取时间并转化为毫秒
            let timestamp = el.textContent
            if (timestamp.length === 10) {
                timestamp = timestamp * 1000
            }
            let value = bindings.value
            if (!value) {
                value = "YYYY-MM-DD HH:mm:ss"
            }
            //2.对时间进行格式化
            const formatTime = dayjs(timestamp).format(value)
            el.textContent = formatTime
        }
    })
}

运行结果

image-20231224183521735