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" 被传入另一个元素。

猜你喜欢

转载自blog.csdn.net/qq_41619796/article/details/114268175