首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法找到使用Vue-Treeselect添加不存在的新项目的方法

无法找到使用Vue-Treeselect添加不存在的新项目的方法
EN

Stack Overflow用户
提问于 2021-03-02 21:26:22
回答 1查看 543关注 0票数 2

我正在尝试创建一个下拉菜单与一个列表,我已经从后端填充。这里是有问题的库Vue Treeselect

一旦用户尝试输入不在内部的内容,我希望能够动态地添加它,稍后当请求被提交时,在后端创建该值。然而,该库似乎没有提供覆盖默认行为的方法。这是我到目前为止尝试过的。

https://codesandbox.io/s/musing-sutherland-i5e8f?fontsize=14&hidenavigation=1&theme=dark

代码语言:javascript
复制
<template>
  <div id="app">
    <div class="container mt-4 mx-auto">
      <treeselect
        @search-change="handleSearch"
        :multiple="true"
        :options="options"
        placeholder="Select your favourite(s)..."
        no-results-text="No results found... Press enter to add"
        v-model="value"
      >
      </treeselect>

      <pre class="bg-gray-200 text-gray-600 rounded mt-4 p-4">{{
        JSON.stringify(value, null, 2)
      }}</pre>

      <h5>Search text: {{ text }}</h5>
      <button
        @click="appendNewItem"
        class="focus:outline-none text-white text-sm py-2.5 px-5 rounded-md bg-blue-500 hover:bg-blue-600 hover:shadow-lg"
      >
        Add
      </button>
    </div>
  </div>
</template>

<script>
// import the component
import Treeselect from "@riophae/vue-treeselect";
// import the styles
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "App",
  components: {
    Treeselect,
  },
  data() {
    return {
      lastId: 0,
      text: "",
      value: [],
      options: [
        { id: 1, label: "Option #1" },
        { id: 2, label: "Option #2" },
      ],
    };
  },
  methods: {
    handleSearch(ev) {
      this.text = ev;
    },
    makeId() {
      return `new-item-${++this.lastId}`;
    },
    appendNewItem() {
      this.options = [...this.options, { id: this.makeId(), label: this.text }];
    },
  },
};
</script>

即使我的按钮解决方案也不起作用,因为一旦您离开树选择输入的区域,文本就会被重置为空字符串,因此按下按钮会添加一个空文本。

根据当前的Vue-Treeselect文档,当用户按下enter而treeselect没有结果时,我如何让它调用我的appendNewItem()函数?

理想情况下,我希望这样做:

代码语言:javascript
复制
<treeselect (other-props)>
    <template #no-results={ node }>
       <span>No results found for {{ node.text }}</span>
       <button @click="appendNewItem">Add {{ node.text }}</button>
    </template>
</treeselect>

但是,不幸的是,库API不支持这一点。它仍然不能解决“按回车键时创建一个新字段”的问题,但无论如何这将是一个很好的开始。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-06 02:11:51

不得不说,这是一个艰难的问题。

该库不提供启用您所描述的功能的方法,但您可以使用一些低级Vue API来重写库方法,并尝试实现所需的效果。

从本质上讲,我们将覆盖库中的select(node)函数,试图使其适应我们的需要。

代码语言:javascript
复制
<script>
import Treeselect from "@riophae/vue-treeselect";

export default {
  extends: Treeselect,
  data() {
    return {
      overridesLastNodeId: 0,
    };
  },
  methods: {
    overridesFindValue() {
      if (this.$refs.control) {
        const childRefs = this.$refs.control.$refs;

        if (childRefs["value-container"]) {
          const valueContainer = childRefs["value-container"];

          if (valueContainer.$refs.input) {
            return valueContainer.$refs.input.value;
          }
        }
      }

      return null;
    },
    overridesCheckValueInNodes(value) {
      let childHasValue = false;

      this.traverseAllNodesDFS((node) => {
        if (node.label === value) {
          childHasValue = true;
        }
      });

      return childHasValue;
    },
    select(node) {
      /**
       * Here we override the select(node) method from
       * the library, we will inject a new node if a node
       * doesn't exist and then proxy this method to the original!
       */
      const value = this.overridesFindValue();
      if (typeof value === "string" && value.length === 0) {
        // This function gets called internally a lot, so we need
        // to make sure it's proxied when there is no value
        return Treeselect.mixins[0].methods.select.call(this, node);
      }

      if (value && value !== "") {
        if (this.overridesCheckValueInNodes(value)) {
          // If there is a value, we just fallback to the default function
          this.resetSearchQuery();
          return Treeselect.mixins[0].methods.select.call(this, node);
        }
      }

      /**
       * Finally, here's the solution to your question.
       * We can emit a new node here, call your append function
       * sending it the ID and making this work.
       */
      const id = `new-node-${++this.overridesLastNodeId}`;
      this.$emit("new-node", { value, id });

      /**
       * Additionally, to make the select select our value
       * we need to "emit" it to v-model as well
       */
      this.$emit("input", [...this.value, id]);

      /**
       * Finally, let's reset the input
       */
      this.resetSearchQuery();
    },
  },
};
</script>

然后,记住在您的代码中使用被覆盖的组件:

代码语言:javascript
复制
<template>
  <div class="container mt-4 mx-auto">
    <treeselect-extended
      :multiple="true"
      :options="options"
      placeholder="Select your favourite(s)..."
      no-results-text="No results found... Press enter to add"
      v-model="value"
      @new-node="appendNewItem"
    />
    <pre class="bg-gray-200 text-gray-600 rounded mt-4 p-4">{{
      JSON.stringify(value, null, 2)
    }}</pre>
  </div>
</template>

<script>
import TreeselectExtended from "./overrides/TreeselectExtended";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "App",
  data() {
    return {
      value: [],
      options: [
        { id: 1, label: "Option #1" },
        { id: 2, label: "Option #2" },
      ],
    };
  },
  components: {
    TreeselectExtended,
  },
  methods: {
    appendNewItem({ value, id }) {
      this.options = [...this.options, { id, label: value }];
    },
  },
};
</script>

这是一个有效的解决方案,但是,我必须建议谨慎使用此代码,因为它创建了与库的内部实现的依赖关系!这意味着,如果您从package.json更新库,即使是次要版本更新,也会给您的项目带来破坏性的更改!因为这段代码甚至依赖于库中的“私有”函数,而不仅仅是面向公众的API。您可以尝试将其用于未来,但更明智的做法可能是选择加入,并使用某些确实能满足您需求的不同库。

这是一个演示这一点的Codesandbox:Link

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66440337

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档