v-bind 的自定义 Vue 指令

问题描述

我目前有这样的事情:

<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' }" />

谢谢!

解决方法

根据documentation

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

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

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

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

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

TL 博士;

好吧,你不能!