How to register component in vue+ts correctly? - javascript

I have this code:
App.vue
<template>
<v-container>
<div>
<schedule-table
v-if = "schedule.length > 0"
:exercises="schedule[0].exercises"
/>
</div>
</v-container>
</template>
<script lang="ts">
import Vue from "vue";
import { Component } from "vue-property-decorator";
import ScheduleTable from '#/components/ScheduleTable.vue'
#Component({
components: {
ScheduleTable,
}
})
</script>
ScheduleTable.vue
<template>
<v-container>
<schedule-week
:exercises="exercises"
/>
</v-container>
</template>
<script lang="ts">
import Vue from "vue";
import { Component, Prop } from "vue-property-decorator";
import { IExercise } from "#/interfaces"
import ScheduleWeek from '#/components/ScheduleWeek.vue'
#Component({
name: 'ScheduleWeek',
components: {
ScheduleWeek,
}
})
#Component
export default class ScheduleTable extends Vue {
#Prop( {required: true, type: Array } ) readonly exercises!: IExercise;
}
</script>
ScheduleWeek.vue
<template>
<v-container
:ex="exercises"
>
here is tables (but this tables dosn't show and any other text dosn't show)
</v-container>
</template>
<script lang="ts">
import Vue from "vue";
import { Component, Prop } from "vue-property-decorator";
import { IExercise } from "#/interfaces"
#Component
export default class ScheduleWeek extends Vue {
#Prop( {required: true, type: Array } ) readonly exercises!: IExercise;
}
</script>
And have vue warn:
Unknown custom element: < schedule-week > - did you register the
component correctly? For recursive components, make sure to provide
the "name" option.
How to fix this problem? How to register component correctly?

There are multiple ways to declare a vue-component when you use typescript. The class-based SFC approach (the one you are using) needs to follow a slightly different syntax. You used the typescript decorator twice in your schedule-week component
App.vue
<v-container>
<div>
<schedule-table
v-if = "schedule.length > 0"
:exercises="schedule[0].exercises"
/>
</div>
</v-container>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator"; // you can import vue here
import ScheduleTable from '#/components/ScheduleTable.vue'
#Component({
components: {
ScheduleTable,
}
})
export default class App extends Vue {} // the #Component() decorator needs to be followed by the exported class
Correspondingly your other components:
ScheduleTable.vue
<template>
<v-container>
<schedule-week
:exercises="exercises"
/>
</v-container>
</template>
<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator"; // see above
import { IExercise } from "#/interfaces"
import ScheduleWeek from '#/components/ScheduleWeek.vue'
#Component({
name: 'ScheduleTable',
components: {
ScheduleWeek,
}
}) // >>>don't use the decorator twice<<<
export default class ScheduleTable extends Vue {
#Prop( {required: true, type: Array } ) readonly exercises!: IExercise;
}
</script>
ScheduleWeek.vue
<template>
<v-container
:ex="exercises"
>
here is tables (but this tables dosn't show and any other text dosn't show)
</v-container>
</template>
<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator"; // see above
import { IExercise } from "#/interfaces"
#Component
export default class ScheduleWeek extends Vue {
#Prop( {required: true, type: Array } ) readonly exercises!: IExercise;
}
</script>
##EDIT:
From the officiel TypeScript Documentation:
With the introduction of Classes in TypeScript and ES6, there now exist certain scenarios that require additional features to support annotating or modifying classes and class members. Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members.
Decorators are basically TypeScript(JavaScript) functions which are used to add additional information to the following class (your component) or class members. This also means a decorator cannot stand alone. The #Component() decorator takes an Object as parameter which is 'as-is' translated into component-options.

TL;DR
To register the components SubOne and SubTwo in MyComponent, pass it to the #Component decorator:
import { Component, Vue } from "vue-property-decorator";
#Component({
components: {
SubOne,
SubTwo,
}
})
export default class MyComponent extends Vue {
…
}
And make sure you also decorate the SubComponents like so;
import { Component, Vue } from "vue-property-decorator";
#Component
export default class SubOne extends Vue {
…
}
Error in #MarcRo's answer
Setup and resulting Error
In the Component ScheduleTable.vue, the decorator #Component gets the parameter name set to the Component it is about to import. This leads to a recursive call of said Component and hence an Error.
Fix
Set name: 'ScheduleTable' - or even drop it. The class name seems to be used (which is what we are doing).
Aside
I could not find a doc on what can actually passed to the decorator, but it's used like this in #MarcRo's answer in App.vue as well as here. (The link in the comments there seems to be old).
I don't have enought reputation to comment and a fixing edit got rejected, so sorry for the extra post.
Thank you #MarcRo for teaching me how to use this and the facepalm moment after solving the recursion error after a way too long time ;)

Related

Cannot access Refs methods from parent component

I have a class component that I use in another parent component. I'm trying to call a method in the child component from the parent component. I'm getting a typeerror saying that the method I am calling is not a function.
Here's the simplified version of my code.
Child Component -
<template>
// HTML Template
</template>
<script>
import { Vue, Component, Ref } from "nuxt-property-decorator";
#Component
export default class ChildComponent extends Vue {
doSomething(){
//do something here
}
}
</script>
Parent Component -
<template>
// HTML template
<child-component refs="child" />
</template>
<script>
import { Vue, Component, Ref } from "nuxt-property-decorator";
import ChildComponent from '/....'
#Component({
components: { ChildComponent }
})
export default class ParentComponent extends Vue {
#Ref("child") readonly child!: ChildComponent;
doAnotherThing(){
//do something here
this.child.doSomething() //this will return typerror that says it;s not a function
}
}
</script>

VueJS nested components fail in an NPM package

The example below are using simplified examples.
Both components work separately, however when one is nested within the other neither render on the page.
index.js (entry point)
// Test components
import TestComponent from '../src/TestComponent.vue'
import Test2Component from '../src/Test2Component.vue'
export {
TestComponent,
Test2Component
}
Both TestComponent and Test2Component will render this way:
<template>
<div class="container">
<TestComponent></TestComponent>
<Test2Component></Test2Component>
</div>
</template>
<script>
import Vue from 'vue'
import { TestComponent, Test2Component } from 'myPackage'
Vue.component('TestComponent', TestComponent);
Vue.component('Test2Component', Test2Component);
However if I move the Test2Component tag into Test1Component.Vue:
<template>
<p>This is the TestComponent</p>
<Test2Component></Test2Component>
</template>
<script>
import Vue from 'vue'
import Test2Component from './Test2Component';
Vue.component('Test2Component', Test2Component);
console.log( Test2Component)
export default {
name: 'TestComponent',
components: {
Test2Component
}
}
</script>
Not even the TestComponent.vue parent component renders.
I found the solution. Do not import Vue from 'vue' and modify it, this is a duplicate of the Vue instance. This syntax seems especially restrictive to get it to work when packaging.
Instead add it as a component to export default:
<script>
import { TestComponent, Test2Component} from 'myPackage'
export default {
components: {
'test-component': TestComponent,
'test2-component': Test2Component
},
...
</script>

Vue.js with TypeScript getting data from Twig error Property does not exist

I'm having trouble printing out the data from Twig template on my Symfony app. I am using Vue.js with TypeScript enabled.
main.ts:
import HeaderNav from './components/HeaderNav.vue'
new HeaderNav({el: '.headnav'});
HeaderNav.vue:
<template>
<div class="headnav headnav-fixed z-depth-1">
{{test}}
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import { Component, Emit, Prop, Watch } from 'vue-property-decorator';
#Component({
props: {
test: {
type: String,
default: "{}"
}
},
mounted: function () {
console.log(this.test);
}
})
export default class HeaderNav extends Vue {}
</script>
header.html.twig:
<div class="headnav" data-test="hello"></div>
I get this error while compiling:
Property 'test' does not exist on type 'Vue'.
Any ideas that am I doing wrong? I am thinking that calling the component HeaderNav first might be the problem, because it instantly overrides the element with class 'headnav', but I am trying to create the components only for separate elements on my site, I don't want to put whole application into Vue.js.
I hope the problem is with you defined props.
In Vue with typescript you need to use props like this:
import { Component, Prop, Vue } from 'vue-property-decorator';
#Component({
name: "HeaderNav"
})
export default class HeaderNav extends Vue {
#Prop({ default: '' }) test!: string;
created(){
console.log(this.test)
}
}
I hope this will help you.
For more information checkout this article: https://blog.logrocket.com/how-to-write-a-vue-js-app-completely-in-typescript/

How to use an external module inside a Vue SFC?

I'm new to Vue, and I'm trying to build an app which uses Typescript and vue-property-decorator. This is my first attempt to use an external module inside an SFC. I want to create a calendar component using v-calendar and render it in a page (schedule.vue).
I've done yarn add, and I'm trying to follow what the docs say about using v-calendar as a component. But as of now, when I try to render the page, there are no compilation errors yet the whole page goes blank. What's going wrong here? Any help is greatly appreciated!
// pages/schedule.vue
<template lang="pug">
VCalendar
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import VCalendar from '../components/calendar.vue';
#Component({
components: {
VCalendar
}
})
export default class Schedule extends Vue {
}
// components/calendar.vue
<template lang="pug">
<v-calendar :attributes="attrs" />
</template>
<script lang="ts">
import 'v-calendar/lib/v-calendar.min.css';
import { Calendar, setupCalendar } from 'v-calendar';
import { Component, Vue } from 'vue-property-decorator';
#Component({
components: {
setupCalendar,
Calendar
}
})
export default class VCalendar extends Vue {
data() {
return {
attrs: [
{
key: 'today',
highlight: {
backgroundColor: '#ff8080',
},
dates: new Date(2018, 0, 1)
}
],
};
}
mounted():any {
setupCalendar({
firstDayOfWeek: 2,
});
}
}
</script>
I've checked these questions but I'm still lost:
How to use external vue npm components
How to include external js inside vue component
You need to register it globally using Vue.component('v-calendar',Calendar ) or in case of class based SFC you are importing Calendar a named import, then it should be used as <calendar></calendar>
#Component({ components: { setupCalendar, 'v-calendar':Calendar } }) can also be used in class based SFCs to provide a custom tag name to some imported component.

Where to import component in Vue?

New to Vue, working off a scaffolded project from the command line. Currently I have:
index.js
import Vue from 'vue'
import Router from 'vue-router'
import Home
from '../components/home'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
}
]
})
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
App.vue
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
<style>
#app {
// default styles are here
}
</style>
And home.vue
<template>
<chart-component></chart-component>
</template>
// rest of home
I am trying to create and import chart-component.vue to use inside home.vue but not sure where to import it at. I've tried adding it in main.js and App.vue unsuccessfully.
chart-component.vue
<template>
<div>
<h1>Testing Chart Component</h1>
</div>
</template>
<script>
export default {
name: 'chart',
data() {
return {
}
}
}
</script>
This seems like a simple problem but unsure how to solve it. My best guess was importing it inside App.vue and adding a components { ChartComponent } underneath the name. Second attempt was importing it into main.js and putting ChartComponent inside components: { App, ChartComponent }.
I would rename your component to ChartComponent from chart-component, as the dash is not a supported character. Vue will properly convert the name to dashes as needed, but when you're searching your code for components, it helps to have consistent names.
anyway. for using a component, you need to import it and define it first
home.vue:
<template>
<ChartComponent></ChartComponent>
</template>
<script>
import ChartComponent from './ChartComponent';
export default {
components: {
ChartComponent
}
}
</script>
Got it to work. Since I only need it locally inside the home.vue component I imported it inside there under data I added
components: {
'chart-component': ChartComponent
}
Importing component becomes much easier in Vue 3 script setup SFCs
<script setup>
import ChartComponent from './components/ChartComponent.vue'
</script>
<template>
<ChartComponent />
</template>

Categories