2.Vue自定义指令参数-修饰符-值/案例-自定义全局指令往数字前添加单位¥

1. 例如:这里 why 是指令名称,kobe 是参数,lazy 是修饰符,message 是值

2. el.textContent 可以拿到页面渲染的数据 ''哈哈哈''

3. bindings.value 可以拿到 message 的值

<template>
  <div class="app">
    <button @click="counter++">+1</button>
    <!-- why是指令名称,kobe是参数,lazy是修饰符,message是值 -->
    <h2 v-why:kobe.lazy="message">哈哈哈</h2>

    <!-- 2.价格拼接单位符号 -->
    <h2 v-unit>{{ 111 }}</h2>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const counter = ref(0)

const message = '你好啊,明天'
const vWhy = {
  mounted(el, bindings) {
    // el.textContent = '你你你你你' // 修改页面的内容
    console.log(bindings, '---bindings---')
    el.textContent = bindings.value  // 把 message 的值渲染到页面上取代了 哈哈哈
  }
}
</script>

<style scoped></style>

4. 往数字前面添加 ¥ 单位,自定义一个全局 v-unit 指令

  • 新建 directives/unit.js

export default function directiveUnit(app) {
  app.directive('unit', {
    mounted(el, bindings) {
      const defaultText = el.textContent
      let unit = bindings.value
      // console.log(unit) // 如果 v-unit 没有传值,则是 undefined
      if (!unit) {
        unit = '¥'
      }
      el.textContent = unit + defaultText
    }
  })
}
  • directives/index.js
import directiveFocus from './focus'
import directiveUnit from './unit'

export default function useDirectives(app) {
  directiveFocus(app)
  directiveUnit(app)
}

main.js

import { createApp } from 'vue'
import App from './01_自定义指令/App.vue'
import useDirectives from './01_自定义指令/directives/index'
// import './assets/main.css'

const app = createApp(App)
// 自定义指令
useDirectives(app)
app.mount('#app')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值