Skip to content
ReferenceVersion 6.0.2

Directives ​

main.ts calls setupDirectives(app). The registrar finds packages/directives/src/modules/<name>/index.ts, calls its default factory, and registers the returned Vue directive under the directory name. Use v-<name> directly in an SFC. The implementation files define each directive's binding type.

Interactive example ​

Try copy, throttle, debounce, ellipsis, ripple, and disabled behavior in one example. The smaller debounce example below shows the call count.

View the full directives example source
tsx
import type { ConditionalPick } from '@/types'
import {
  NAlert,
  NButton,
  NCard,
  NFlex,
  NForm,
  NFormItem,
  NInput,
  NInputGroup,
  NInputNumber,
  NSwitch,
} from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'

const RDirective = defineComponent({
  name: 'RDirective',
  setup() {
    const state = reactive({
      copyValueOne: '我是待复制内容区域一',
      copyValueTwo: '我是待复制内容区域二',
      throttleBtnClickCount: 0,
      debounceBtnClickCount: 0,
      disabledValue: false,
      formCount: 0,
    })
    const ellipsisLineClamp = ref(2)

    const updateDemoValue = (
      key: keyof ConditionalPick<typeof state, number>,
    ) => {
      state[key]++
    }

    return {
      ...toRefs(state),
      updateDemoValue,
      ellipsisLineClamp,
    }
  },
  render() {
    return (
      <DemoPage
        title={this.$t('menu.Directive')}
        description={this.$t('showcase.directiveDescription')}
        eyebrow="RAY TEMPLATE / EXAMPLES"
      >
        <div class="r-demo-grid">
          <NCard title={this.$t('demoDetails.directive.ripple')}>
            <NFlex vertical>
              <NFlex>
                <NButton v-ripple type="info">
                  {this.$t('demoDetails.directive.ripplePointer')}
                </NButton>
                <NButton v-ripple={[true, ['center']]}>
                  {this.$t('demoDetails.directive.rippleCenter')}
                </NButton>
              </NFlex>
            </NFlex>
          </NCard>
          <NCard title={this.$t('demoDetails.directive.ellipsis')}>
            <NFlex vertical>
              <NCard title={this.$t('demoDetails.directive.single')}>
                <div
                  v-ellipsis={{
                    type: 'block',
                    width: '100px',
                  }}
                >
                  我是一段很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长的文本。
                </div>
              </NCard>
              <NCard title={this.$t('demoDetails.directive.multi')}>
                <NFlex vertical size="large">
                  <NAlert title="注意" type="warning">
                    该方法基于非标准属性实现(-webkit-line-clamp),可能会有兼容性问题,所以请谨慎使用。
                    详情参考:
                    <a href="https://caniuse.com/?search=line-clamp">
                      can i use
                    </a>
                  </NAlert>
                  <div
                    v-ellipsis={{
                      type: 'line',
                      width: '100px',
                      line: this.ellipsisLineClamp,
                    }}
                  >
                    我是一段很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长的文本。
                  </div>
                  <NInputNumber
                    v-model:value={this.ellipsisLineClamp}
                    min={1}
                  />
                </NFlex>
              </NCard>
            </NFlex>
          </NCard>
          <NCard title={this.$t('demoDetails.directive.copy1')}>
            <NInputGroup>
              <NInput v-model:value={this.copyValueOne} />
              <NButton v-copy={this.copyValueOne}>
                {this.$t('demoDetails.directive.copy')}
              </NButton>
            </NInputGroup>
          </NCard>
          <NCard title={this.$t('demoDetails.directive.copy2')}>
            <NInputGroup>
              <NInput v-model:value={this.copyValueTwo} />
              <NButton v-copy={this.copyValueTwo}>
                {this.$t('demoDetails.directive.copy')}
              </NButton>
            </NInputGroup>
          </NCard>
          <NCard title={this.$t('demoDetails.directive.throttle')}>
            <NFlex vertical>
              <NButton
                v-throttle={{
                  func: this.updateDemoValue.bind(
                    null,
                    'throttleBtnClickCount',
                  ),
                  trigger: 'click',
                  wait: 3000,
                  options: {},
                }}
              >
                {this.$t('demoDetails.directive.run')}
              </NButton>
              <DemoResult label={this.$t('demoDetails.directive.calls')}>
                {this.throttleBtnClickCount}
              </DemoResult>
            </NFlex>
          </NCard>
          <NCard title={this.$t('demoDetails.directive.debounce')}>
            <NFlex vertical>
              <NButton
                v-debounce={{
                  func: this.updateDemoValue.bind(
                    null,
                    'debounceBtnClickCount',
                  ),
                  trigger: 'click',
                  wait: 3000,
                  options: {},
                }}
              >
                {this.$t('demoDetails.directive.run')}
              </NButton>
              <DemoResult label={this.$t('demoDetails.directive.calls')}>
                {this.debounceBtnClickCount}
              </DemoResult>
            </NFlex>
          </NCard>
          <NCard title={this.$t('demoDetails.directive.disabled')}>
            <NFlex vertical>
              <NSwitch v-model:value={this.disabledValue}>
                {{
                  checked: () => '取消',
                  unchecked: () => '禁用',
                }}
              </NSwitch>
              <NCard title={this.$t('demoDetails.directive.nativeForm')}>
                <form
                  v-disabled={this.disabledValue}
                  onSubmit={(event) => {
                    event.preventDefault()
                    this.formCount += 1
                  }}
                >
                  <NInputGroup>
                    <NInput
                      inputProps={{
                        'aria-label': this.$t(
                          'demoDetails.directive.formInput',
                        ),
                      }}
                    />
                    <NButton attrType="submit">
                      {this.$t('demoDetails.directive.submit')}
                    </NButton>
                  </NInputGroup>
                </form>
                <DemoResult label={this.$t('demoDetails.directive.calls')}>
                  {this.formCount}
                </DemoResult>
              </NCard>
              <NCard title={this.$t('demoDetails.directive.text')}>
                <NFlex vertical>
                  <p v-disabled={this.disabledValue}>
                    我是可以被禁用的文本内容
                  </p>
                </NFlex>
              </NCard>
              <NCard title={this.$t('demoDetails.directive.naive')}>
                <NFlex vertical justify="start">
                  <NForm v-disabled={this.disabledValue}>
                    <NFormItem>
                      <NInput />
                    </NFormItem>
                  </NForm>
                  <NButton v-disabled={this.disabledValue}>按钮</NButton>
                  <NSwitch v-disabled={this.disabledValue}></NSwitch>
                </NFlex>
              </NCard>
            </NFlex>
          </NCard>
        </div>
      </DemoPage>
    )
  },
})

export default RDirective

v-copy ​

Bind the string to copy. Changing the binding recreates the ClipboardJS instance, and unmounting destroys it. Ray Admin supplies notifications when registering the directive. Standalone consumers of createCopyDirective can supply their own callbacks. Trigger copy from a user click. Convert nonstring values such as numbers explicitly.

vue
<template>
  <button type="button" v-copy="'ORD-001'">Copy order number</button>
</template>

Source

v-debounce and v-throttle ​

Click the button repeatedly. Debounce calls the handler once after 500 ms without further clicks.

Calls: 0
View example source
vue
<template>
  <DemoFrame>
    <div class="ray-demo">
      <NButton v-debounce="{ wait: 500, func: increment }">
        {{ english ? 'Click repeatedly' : '连续点击' }}
      </NButton>
      <output class="ray-demo-result">
        {{ english ? 'Calls' : '执行次数' }}: {{ calls }}
      </output>
    </div>
  </DemoFrame>
</template>

<script setup lang="ts">
import debounce from '@ray-template/directives/debounce'
import { NButton } from 'naive-ui'
import { useData } from 'vitepress'
import { computed, ref } from 'vue'
import DemoFrame from './DemoFrame.vue'

const { lang } = useData()
const english = computed(() => lang.value.startsWith('en'))
const vDebounce = debounce()
const calls = ref(0)
const increment = () => {
  calls.value += 1
}
</script>

Both directives accept { func, trigger?, wait?, options? }. func must be a function and can accept the native event. trigger defaults to 'click', wait to 500 ms, and options passes through to the corresponding Lodash method. Debounce handles input after a burst stops. Throttle limits a continuing event rate.

vue
<script setup lang="ts">
import { ref } from 'vue'

const keyword = ref('')
const requestedKeyword = ref('')
const clicks = ref(0)

const applySearch = () => {
  requestedKeyword.value = keyword.value
}
const countClick = () => {
  clicks.value += 1
}
</script>

<template>
  <input
    v-model="keyword"
    v-debounce="{ func: applySearch, trigger: 'input', wait: 300 }"
  />
  <p>Submitted query: {{ requestedKeyword }}</p>
  <button type="button" v-throttle="{ func: countClick, wait: 1000 }">
    Clicks: {{ clicks }}
  </button>
</template>
  • options.leading and trailing control execution at the start and end of the interval. Debounce also supports maxWait. The directive reads the binding on mount. For changing data, read reactive values inside the original callback.
  • Each bound element has independent timing. Unmounting removes its own listener and queued callback. Change the element's key to bind a new interval.
  • These directives control how often handlers fire. Manage cancellation, concurrency, and idempotency separately for async requests.

Debounce source · Throttle source

v-ellipsis ​

width is required. Numbers are pixels and strings can be CSS lengths. type: 'block' truncates one line. type: 'line' uses the line count, with one line as the default. popoverText: true writes the current text to the native title. Styles are written on mount and update. Switching modes or disabling hover text can leave the previous styles or title. For frequent changes, use the UI library's ellipsis component or change the node's key.

vue
<template>
  <p v-ellipsis="{ type: 'line', line: 2, width: 240, popoverText: true }">
    Longer explanatory text is truncated after two lines.
  </p>
</template>

Source

v-ripple ​

Omit the binding or pass true to enable, and use false to disable. Supply { class: '...' } to style the ripple. .center starts it in the center, and .circle uses circular geometry. Pointer events draw the visual feedback. The wrapping button owns the interaction semantics.

vue
<template>
  <button type="button" v-ripple.center.circle>View details</button>
</template>

Source · Binding and cleanup

v-disabled ​

Native form controls use the Boolean disabled attribute. Forms, containers, and custom control roots use inert, removing the subtree from keyboard focus and blocking pointer interaction. Set the binding back to false to restore interaction. Prefer the component's own disabled prop when available.

Source

Add a directive ​

Put each directive in its own directory and default-export the factory. Use CustomDirectiveFC<HTMLElement, T> to type the binding. Read the element in mounted, handle changes in updated, and release listeners, timers, and third-party instances in beforeUnmount. Store per-element resources in a WeakMap when bindings are independent.

ts
import type { CustomDirectiveFC } from '@/directives/types'

const focusWhen: CustomDirectiveFC<HTMLElement, boolean> = () => ({
  mounted(el, { value }) {
    if (value) el.focus()
  },
  updated(el, { value, oldValue }) {
    if (value && !oldValue) el.focus()
  },
})

export default focusWhen

Save the example as packages/directives/src/modules/focus-when/index.ts and use v-focus-when. Use a single lower-case kebab-case directory name. The registrar throws if the default export is missing or is not a function.

Registration entry point · Directive types