在vue和nuxt js中使用多个道具创建带有子项的全局组件

时间:2019-07-10 07:17:50

标签: vuejs2 nuxt.js

我正在尝试构建具有子项和多个道具的全局组件,以实现多种用途。我不知道我在哪里犯错。这是我的组件文件

  

SectionHeading.vue

<script>
import Vue from 'vue'
import Heading from '~/components/Heading.vue'

  Vue.component('SectionHeading', {
    props: {
      heading: [String],
      content: [String]
    },
    template: '<div><Heading>{{ heading }}</Heading><p>{{ content }}</p></div>'
    // this may be not necessary
  })

  export default {
    components: {
      Heading
    }
  }
</script>

<template>
  <b-container class="text-center">
      <span><img src="~/assets/images/Icon.svg" alt="" /></span>
      <Heading :level="3">{{ heading }}</Heading>
      <p>{{ content }}</p>
  </b-container>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">

</style>

这是我的index文件,我正在导入SectionHeading组件

  

index.vue

<template>
  <section class="">
    <SectionHeading heading="About Me" content="lorem ipsum" />
  </section>
</template>

<script>
  import SectionHeading from '~/components/SectionHeading.vue'
  export default {
    components: {
      SectionHeading
    },
    data () {
      return {
        title: 'Home'
      }
    },
    head () {
      return {
        title: this.title
      }
    }
  }
</script>
<style>

</style>

我希望其显示如下

<div class="contaniner">
  <span><img src="images/Icon.svg" alt="" /></span>
  <h3>About Me</h3>
  <p>lorem ipsum</p>
</div>

我所得到的是

<div class="container">
 <span><img src="images/Icon.svg" alt="" /></span>
 <h3></h3>
 <p></p> 
</div>

我得到enter image description here的错误

1 个答案:

答案 0 :(得分:1)

我认为您正在做这件事,并且当您确实应该以“ Nuxt方式”进行操作时,尝试以“ Vue方式”创建全局组件。

“ Nuxt方式”将如下所示:

//components/SectionHeading.vue
<script>
import Heading from '~/components/Heading.vue'

export default {
  props: ['heading', 'content'],
  components: {
    Heading
  }
}
</script>

<template>
  <b-container class="text-center">
      <span><img src="~/assets/images/Icon.svg" alt="" /></span>
      <Heading :level="3">{{ heading }}</Heading>
      <p>{{ content }}</p>
  </b-container>
</template>

<style scoped lang="scss">

</style>

然后您要在plugins目录中创建一个文件,将其命名为global.js

//plugins/global.js
import Vue from 'vue'
import SectionHeading from '~/components/SectionHeading.vue'

Vue.component('section-heading', SectionHeading)

然后在nuxt.config.js中注册该插件

//nuxt.config.js
...
plugins: [ '@/plugins/global.js' ]
...

,您应该有权在任何页面中将其用作

<section-heading heading="blah" content="blah more"/>