Vue2树选择Ajax调用无法加载选项

时间:2018-02-22 05:56:54

标签: javascript laravel-5 vuejs2 axios

我正在尝试使用此库以树的形式获取动态输入元素 https://riophae.github.io/vue-treeselect/#basic-features

我的选项将通过对Laravel后端的ajax调用生成。

我的Vue2组件代码是这样的,

<template lang="html">
  <div>
    <div class="" >
      <treeselect :multiple="true"  :options="options"   :flat="true" :sort-value-by="sortValueBy"  :default-expand-level="1"
      placeholder="Try selecting some options."        v-model="value"   />
      <pre class="result">{{ value }}</pre>
    </div>

</div>
</template>
<script>
import Treeselect from '@riophae/vue-treeselect'

function tests(id) {
  var data = [];
  axios.get('/standards/' + id + '/tests')
    .then(function(response) {
      data: response.data;
    });
  return data;
}

let called = false

export default {
  components: {
    Treeselect,
  },

  data() {
    return {
      value: null,
      options: tests(1)
      sortValueBy: 'ORDER_SELECTED',
    }
  },
  methods: {
    loadRootOptions(callback) {
      axios.get('/standards/1/tests')
        .then(response => rootOptions = response.data);
    },
  },
}
</script>

<style src="@riophae/vue-treeselect/dist/vue-treeselect.min.css"></style>

Laravel Backend就像这样

public function tests($id)
    {
        $tests = [['id'=>'a','label'=>'sandeep'],['id'=>'b','label'=>'sandeep']];
        return $tests;
    }

来自后端的JSON响应是正确的。 问题在于使用此树选择库通过ajax调用动态加载选项。

KIndly帮助使用正确的代码,因为我不熟悉使用Vue。

1 个答案:

答案 0 :(得分:0)

如果您仍然需要帮助,请不确定这是否在8个月前可用。 所有这些代码都可以在https://vue-treeselect.js.org/#delayed-loading

上找到。
  <treeselect
        v-model="value"
        :options="options"
        :load-options="loadOptions"
        :auto-load-root-options="false"
        :multiple="true"
        placeholder="Open the menu..."
    />



 import { LOAD_ROOT_OPTIONS } from '@riophae/vue-treeselect'
 import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'

然后在方法中添加loadOptions

        loadOptions({ action, parentNode, callback }) {

            if (action === LOAD_CHILDREN_OPTIONS) {
                        parentNode.children = [ {
                            id: 'child',
                            label: 'Child option',
                        } ]
                        callback()
            }

            if (action === LOAD_ROOT_OPTIONS) {

                this.options =  [ 'a', 'b', 'c', 'd', 'e' ].map(id => ({
                    id,
                    label: `option-${id}`,
                }));

                callback();
            }
        },