最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically assign directives via an object in vue - Stack Overflow

programmeradmin4浏览0评论

If I have a ponent in vue:

<template>
    <ponent v-bind="dynamicAttrs"></ponent>
</template>

And I want to assign some dynamic attributes to it where v-demo is a custom directive:


data() {
  return {
    dynamicAttrs: {
      'class': 'foo'
      'v-demo': true
    }
  }
}

Although I can see the attbitues in the dom the custom directive is not firing in this scenario.

Is there a way I can dynamically assign directives via an object in vue?

If I have a ponent in vue:

<template>
    <ponent v-bind="dynamicAttrs"></ponent>
</template>

And I want to assign some dynamic attributes to it where v-demo is a custom directive:


data() {
  return {
    dynamicAttrs: {
      'class': 'foo'
      'v-demo': true
    }
  }
}

Although I can see the attbitues in the dom the custom directive is not firing in this scenario.

Is there a way I can dynamically assign directives via an object in vue?

Share Improve this question asked Mar 3, 2021 at 17:27 rndwarerndware 2134 silver badges10 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

v-bind is a directive. You can't apply a directive with another directive

It is true what Michael said but maybe you can work around it a bit:

<template>
    <ponent :is="customComponentName" :data="dynamicAttrs"></ponent>
</template>

then you can create a custom ponent that renders based on the data you put in. https://v2.vuejs/v2/guide/ponents.html#Dynamic-Components

option 2:

create an custom directive and put the dynamic values in the arguments:

<template>
    <ponent v-demo:[show]="dynamicMethod" :class="{}" />
</template>

https://v2.vuejs/v2/guide/custom-directive.html#Dynamic-Directive-Arguments

You could do in this manner if you genuinely want this(Just recently, I had the same thing). Although it yikes a little, but it works. If you have more directives, it bees ugly

发布评论

评论列表(0)

  1. 暂无评论