简体   繁体   中英

How do I pass data to a component using Props in Vue2?

I have created a.Vue file to feature information on a cafe (Cafe Details Page). However, I would like to take parts of this details page and make it its own component, in order to manage any template updates more efficiently.

Therefore, I have created a Component (CafeHeader.vue) inside a components folder. I am trying to pass down the data from my array (Which is being used on my Cafe Details page) to this component using Props. However, I can't seem to get it to work.

The template for my Cafe Details Page is as below:

<template>
    <div>
        <div v-for="cafe in activeCafe">
            <CafeHeader v-bind:cafes="cafes" />
            <div class="content">
                <p>{{ cafe.cafeDescription }}</p>
            </div>
        </div>
    </div>
</template>

<script>
import CafeHeader from "./../../components/CafeHeader";
import cafes from "./../../data/cafes"; // THIS IS THE ARRAY
export default {
    data() {
        return {
            cafes: cafes
        };
    },
    components: {
        CafeHeader,
    },
    computed: {
        activeCafe: function() {
            var activeCards = [];
            var cafeTitle = 'Apollo Cafe';
            this.cafes.forEach(function(cafe) {
                if(cafe.cafeName == cafeTitle){
                    activeCards.push(cafe);
                }
            });
            return activeCards;
        }
    }
};
</script>

Then, in a components folder I have a component called CafeHeader where I am wanting to use the data from the array which is previously imported to the Cafe Details page;

<template>
    <div>
        <div v-for="cafe in cafes">
            <h1>Visit: {{cafe.cafeName}} </h1>
        </div>
    </div>
</template>

<script>
        export default {
  name: "test",
  props: {
      cafes: {
          type: Array,
          required: true
      }
  },
  data() {
      return {
          isActive: false,
          active: false
      };
  },
  methods: {}
};
</script>

If in the CafeHeader component I have cafe in cafes , it does render data from the cafes.js However, it is every cafe in the list and I want just a single cafe.

<template>
    <div>
        <div v-for="cafe in cafes">
            <h1>Visit: {{cafe.cafeName}} </h1>
        </div>
    </div>
</template>

The component also needed activeCafes on the v-for

<template>
    <div>
        <div v-for="cafe in activeCafes">
            <h1>Visit: {{cafe.cafeName}} </h1>
        </div>
    </div>
</template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM