Subscribe on changes!

render 函数中动态添加指令报错

avatar
Dec 8th 2021

Version

3.2.24

Reproduction link

codesandbox.io

Steps to reproduce

打开页面控制台报错。

import { createApp, h, withDirectives, resolveDirective } from "vue";

createApp({
  data() {
    return {
      flag: false
    };
  },
  directives: {
    bg(el, binding) {
      el.style.background = binding.value;
    },
    text(el, binding) {
      el.innerText = binding.value;
    }
  },

  mounted() {
    setTimeout(() => (this.flag = true), 10);
  },

  render() {
    let div = h("div", {
      style: "width:100px;height:100px;border:1px solid;"
    });
    const bg = resolveDirective("bg");
    const text = resolveDirective("text");
    let dirs = [[bg, "red"]];
    if (this.flag) {
      dirs.push([text, "test"]);
    }
    return withDirectives(div, dirs);
  }
}).mount("#app");

What is expected?

在 render 中能够动态添加指令。

What is actually happening?

vnode 上绑定的新指令数组与旧指令的数组不一致导致报错。

avatar
Dec 8th 2021

I'm not sure whether this is legal, it seems not been discussed, maybe involve directive's lifecycle. 不知道能不能增减绑定的指令,这似乎没有讨论过,可能涉及到指令的生命周期,不过你可以先暂时用一个指令传参代替。

avatar
Dec 10th 2021

This is not supported. Directives must be constantly applied.