我在SpotifyButton
目录中有一个名为components
的组件,如下所示:
<template functional>
<b-button pill size="sm" :href="props.spotifyUri" class="spotify-green">
<b-img-lazy
src="~/assets/Spotify_Icon_RGB_White.png"
height="20"
width="20"
/>
View on Spotify
</b-button>
</template>
<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
name: 'SpotifyButton',
props: {
spotifyUri: {
type: String,
required: true
}
}
});
</script>
我能够像这样毫无问题地在pages
目录中的组件中导入和使用它:
<template>
<spotify-button :spotify-uri="artist.uri"/>
</template>
<script lang="ts">
import Vue from 'vue';
import { Context } from '@nuxt/types';
import FullArtist from '@/types/FullArtist';
import SpotifyButton from '@/components/SpotifyButton.vue';
export default Vue.extend({
name: 'ArtistPage',
components: {
SpotifyButton
},
async asyncData({ $axios, params, error }: Context) {
try {
const artist: FullArtist = await $axios.$get(`/api/artists/${params.id}`);
return { artist };
} catch (e) {
error({ statusCode: 404, message: 'Artist not found' });
}
},
data() {
return {
artist: {
name: ''
} as FullArtist
};
}
});
</script>
但是,如果我尝试以相同方式将SpotifyButton
导入到components
目录中的另一个组件中,则会出现以下错误。
这里是ArtistPreview
组件,它位于components
目录中:
<template functional>
<spotify-button :spotify-uri="props.artist.uri"/>
</template>
<script lang="ts">
import Vue, { PropType } from 'vue';
import SpotifyButton from '@/components/SpotifyButton.vue';
import SimpleArtist from '@/types/SimpleArtist';
export default Vue.extend({
name: 'ArtistPreview',
components: {
SpotifyButton
},
props: {
artist: {
type: Object as PropType<SimpleArtist>,
required: true
}
}
});
</script>
我错过了什么吗?为什么在pages
目录组件中可以正常工作的导入在components
目录组件中不能正常工作?
答案 0 :(得分:0)
继续:
import SpotifyButton from '~/components/SpotifyButton.vue'
使用Typescript最好使用另一种方法:添加“ nuxt-property-decorator”并遵循其流程。
因此,您按以下方式定义组件:
<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator'
import SpotifyButton from '~/components/SpotifyButton.vue'
@Component({
components: {
SpotifyButton
},
})
class AnotherComponent extends Vue {
...
}
export default AnotherComponent
</script>
[Nuxt Property Decorator on Github][1]
I think is important to read the official [Nuxt Typescript documentation][2] to a proper setup.
I hope it helps!
[1]: https://github.com/nuxt-community/nuxt-property-decorator
[2]: https://typescript.nuxtjs.org/
答案 1 :(得分:0)
您只需要尝试
components: {
"spotify-button":SpotifyButton
}
答案 2 :(得分:0)
发生这种情况是因为我正在使用功能组件。事实证明,如果不采取一些时髦的解决方法,就无法嵌套功能组件。这是GitHub issue,其中包含一些解决方案。
我采用了第一个解决方案,所以我的ArtistPreview
组件现在看起来像这样:
<template functional>
<spotify-button :spotify-uri="props.artist.uri"/>
</template>
<script lang="ts">
import Vue, { PropType } from 'vue';
import SpotifyButton from '@/components/SpotifyButton.vue';
import SimpleArtist from '@/types/SimpleArtist';
Vue.component("spotify-button", SpotifyButton);
export default Vue.extend({
name: 'ArtistPreview',
props: {
artist: {
type: Object as PropType<SimpleArtist>,
required: true
}
}
});
</script>