【问题标题】:Custom Vue Directive For v-bindv-bind 的自定义 Vue 指令
【发布时间】:2021-04-23 11:07:53
【问题描述】:

我目前有这样的事情:

<q-input v-model="value" label="Some Label" v-bind="getDefaults('someId')" />

getDefaults() 在哪里:

function getDefaults (id) {
  return {
      'id': id,
      'clearable': true,
      'lazy-rules': true,
      'outlined': true,
      'class': 'form-padding'
       // more props/parameters
   }
}

现在,我想将 v-bind 转换为自定义指令。

export const sampleDirective = {
  inserted: function (el, binding) {
    // this doesn't work
    el.class += 'form-padding'
    // how to set id from here
    // and how to set the props as well (like ```clearable```, ```lazy-rules```, etc)?
  }
}

那么如何从自定义指令中设置这些参数/道具,以便我可以这样调用它:

<q-input v-model="value" label="Some Label" v-sampleDirective="{ id: 'someId' }" />

谢谢!

【问题讨论】:

    标签: vue.js vue-directives


    【解决方案1】:

    根据documentation

    请注意,在 Vue 2.0 中,代码重用和抽象的主要形式是组件——但是在某些情况下,您可能需要对普通元素进行一些低级 DOM 访问,而这仍然是自定义指令有用的地方。

    所以有一件事很清楚,道具是不可能的;您必须使用默认提供的指令,例如 v-bind,因为您无法访问/更改除原始 DOM 元素之外的任何内容。默认提供的指令在编译组件以呈现功能时有所不同;其中自定义指令的工作方式不同,只允许修改 DOM 元素。

    为了更清楚,v-ifv-else 等指令用于在渲染函数中转换为 javascript if-else 子句的模板中,类似地 v-for 在渲染函数中转换为 for 循环。

    作为 DOM 元素的类、id 和其他属性的问题,您可以使用原生 javascript DOM API(如 element.classList.add("my-class")element.setAttribute('id', 'something') 等)修改这些属性。

    注意:我个人对命名custom directive的看法导致包括我自己在内的一些人的困惑,custom directive相当于vue的指令v-for,可以由API用户构造,事实并非如此。

    TL 博士;

    你不能!

    【讨论】:

      猜你喜欢
      • 2018-10-20
      • 2019-11-06
      • 2021-12-07
      • 2018-02-20
      • 1970-01-01
      • 2018-04-11
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多