Vuejs:动态递归组件

时间:2018-02-13 11:22:06

标签: javascript recursion vue.js vuejs2 components

我正在尝试创建一个自我调用的自定义组件。我一直收到错误

Unknown custom element: <TestRec> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

我已经包含了一个名称选项,如下所示,但这并没有解决问题。

知道它可能是什么吗?

<template>
  <div>
        <h4>I am a component that can call itself below</h4>

        <v-select :items="['TestRec', 'normal']" v-model="comp"></v-select>

        <hr />
        <component :is="comp"></component>
  </div>
</template>

<script>
import TestRec from "./TestRec";
export default {
    name: 'New-Test-Rec', //Name tried 'Test-Rec' too. Same result
    components: {
        TestRec
    },
    data(){
        return {
            comp: null
        }
    }
}
</script>

1 个答案:

答案 0 :(得分:3)

当我删除components密钥并使用其名称调用它时,为我工作。这里是a running example in code sandbox,以下是未来参考的代码:

<template>
    <div class="hello">
        <h4>I am a component that can call itself below</h4>
        <button @click="show = true">Load next</button>
    <hr />
    <component v-if="show" :is="'TestRec'"></component>
    </div>
</template>

<script>
    export default {
  name: 'TestRec',
  data() {
    return {
      msg: 'Welcome to Your Vue.js App',
      show: false
    }
  }
}

</script>