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')

猜你喜欢

转载自blog.csdn.net/m0_62323730/article/details/129975503