将组件导入Vue,然后传递数据

时间:2018-12-19 20:47:26

标签: vue.js vuejs2 vue-component nuxt.js

我的Nuxt项目中有一个组件。

components / Boxes.vue:

<template>
  <b-container>
    <b-row>
        <b-col v-for="box in boxes" v-bind:key="box">
          <b-card 
          :title="box.title"
          class="text-center mt-5">
            <p class="card-text">
              {{ box.text }}
            </p>
            <b-button
            variant="danger"
            >Find out more</b-button>
          </b-card>
        </b-col>
    </b-row>
  </b-container>
</template>

<script>
export default {
  name: "Boxes",
  data() {
    return {
    }
  }
}
</script>

然后我要将其导入pages / index.vue

<template>
<div id="home">
  <b-container>
    <b-carousel 
      id="carousel1"
      class="mt-2"
      style="text-shadow: 1px 1px 2px #333;"
      controls
      indicators
      background="#ababab"
      :interval="4000"
      img-width="1024"
      img-height="480"
      v-model="slide"
      @sliding-start="onSlideStart"
      @sliding-end="onSlideEnd"
    >
      <b-carousel-slide img-src="./slides/slide1.jpg"></b-carousel-slide>
      <b-carousel-slide img-src="./slides/slide2.jpg"></b-carousel-slide>
      <b-carousel-slide img-src="./slides/slide3.jpg"></b-carousel-slide>
      <b-carousel-slide img-src="./slides/slide4.jpg"></b-carousel-slide>
    </b-carousel>
  </b-container>
  <Boxes/>
</div>
</template>

<script>
import Boxes from '@/components/Boxes.vue';

export default {
  components: {
    Boxes
  },
  data () {
    return {
      slide: 0,
      sliding: null,
      boxes: [
        {
          title: 'Fire Stopping',
          text: 'How does it work?'
        },
        {
          title: 'Our Services',
          text: 'Full range of firestopping'
        },
        {
          title: 'Bid Request',
          text: 'Inexpensive peace of mind'
        },
      ]
    }
  },
  methods: {
    onSlideStart (slide) {
      this.sliding = true
    },
    onSlideEnd (slide) {
      this.sliding = false
    }
  }
}
</script>

试图将它加载到index.vue文件时,好像没有导入它。

您看到它在这里运行,因此您可以更好地了解:https://codesandbox.io/s/github/perfectimprints/precisionfirestopping.com

Vue抱怨该组件未定义,但已在渲染器上注册。

1 个答案:

答案 0 :(得分:2)

您缺少将boxes道具传递给组件的信息:

    <Boxes :boxes="boxes" />

,然后在组件内部添加props:['boxes'],如:

   <script>
      export default {
        name: "Boxes",
        props:['boxes'],
        data() {}
       }
    </script>

选中此code

您可以了解doc1doc2中的props以及如何将数据从父级传递到子级