I'm working on a small project using VueJs And I would like to render my component dynamically.
I tried in my index.vue:
<component v-bind:is="text"></component>
But I got an error: Property or method "text" is not defined on the instance but referenced during render
Since I registered my component in app.js ( globally ) like that :
Vue.component('text', () => import('./components/forms/Text'));
Property or method "text" is not defined on the instance but referenced during render
You did not define text in data. Check this example
// Text1.vue
<template>
<div>
<h1>I am Text 1</h1>
</div>
</template>
// Text2.vue
<template>
<div>
<h1>I am Text 2</h1>
</div>
</template>
// App.vue
<template>
<div id="app">
// dynamic component
<component v-bind:is="currentComponent" />
<button v-on:click="toggle">Toggle</button>
</div>
</template>
<script>
import Text1 from "./Text1.vue";
import Text2 from "./Text2.vue";
export default {
name: 'App',
components: {
Text1,
Text2,
},
data() {
return {
// define property to track which component is active
currentComponent: "Text1",
};
},
methods: {
// toggle between component
toggle() {
if (this.currentComponent === Text1) {
this.currentComponent = Text2;
} else {
this.currentComponent = Text1;
}
},
},
}
</script>
And define it globally
Vue.component('my-dynamic-component', { /* ... */ })
// you must also use kebab-case when referencing its <my-dynamic-component />
or
Vue.component('MyDynamicComponent', { /* ... */ })
// both <my-dynamic-component> and <MyDynamicComponent> are acceptable