vue3.0でのカスタム命令の使用

序文:

       vue3.0のカスタム手順を使用してください。

実装手順:(クリックのカスタム属性をグローバルに定義します)

1. src /   新しいフォルダディレクティブ、新しい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!"
})

 

コンポーネントで使用

また、属性の非プロパティ 同様に、アセンブリで使用される場合、カスタム命令は常にヘッドノードアセンブリに適用されます。

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

1

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

 

属性とは異なり、命令v-bind="$attrs" を別の要素に渡すことはできません 

おすすめ

転載: blog.csdn.net/qq_41619796/article/details/114268175