vue3.0中自定义指令的使用

前言:

       在vue3.0中使用我们的自定义指令。

实现步骤:(全局定义点击的自定义属性)

1、src/   新建文件夹 directives,新建index.js

export default (app) => {
  //自定义组件
  app.directive('demo', (el, binding) => {
    el.addEventListener('click', () => {
      console.log(binding.value.color) // => "white"
      console.log(binding.value.text) // => "hello!"
    })
  })
}

2、main.js中

import directives from './directives/index.js'

const app = createApp(App)
directives(app)

3、页面使用

<el-button v-demo="{ color: 'white', text: 'hello!' }">自定义指令</el-button>

4、点击按钮,f12中显示

官方介绍:点我进入

官方介绍详情:

函数简写

在前面的例子中,你可能想在 mounted 和 updated 时触发相同行为,而不关心其他的钩子函数。那么你可以通过将这个回调函数传递给指令来实现:

app.directive('pin', (el, binding) => {
  el.style.position = 'fixed'
  const s = binding.arg || 'top'
  el.style[s] = binding.value + 'px'
})

 

#对象字面量

如果指令需要多个值,可以传入一个 JavaScript 对象字面量。记住,指令函数能够接受所有合法的 JavaScript 表达式。

<div v-demo="{ color: 'white', text: 'hello!' }"></div>

 

app.directive('demo', (el, binding) => {
  console.log(binding.value.color) // => "white"
  console.log(binding.value.text) // => "hello!"
})

 

#在组件中使用

非 prop 的 attribute 类似,当在组件中使用时,自定义指令总是会被应用在组件的根节点上。

<my-component v-demo="test"></my-component>

1

app.component('my-component', {
  template: `
    <div> // v-demo 指令将会被应用在这里
      <span>My component content</span>
    </div>
  `
})

 

和 attribute 不同,指令不会通过 v-bind="$attrs" 被传入另一个元素。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浩星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值