首页 > 解决方案 > VueJS,将数据从组件传递到另一个

问题描述

我为我做了一些新的东西,我有问题..所以让我们解释一下..

我有名称的组件components/HomeComponent.vue

这是:

主页组件.vue

<script>
export default {
  name: "HomeComponent",
  data() {
    posts: [
      { title: "Hello", body: "Some text" },
      { title: "Hello", body: "Some text" },
      { title: "Hello", body: "Some text" },
      { title: "Hello", body: "Some text" }
    ];
  }
};
</script>

我有我的“观点”views/Home.vue

主页.vue

<template>
  <!-- Blog Entries Column -->
  <div class="col-md-8">
    <h1 class="my-4">Статии</h1>

    <!-- Blog Post -->
    <div class="card mb-4" v-for="post in posts">
      <div class="card-body">
        <h2 class="card-title">{{ post.title }}</h2>
        <p class="card-text">{{ post.body }}</p>
        <a href="#" class="btn btn-primary">Read More &rarr;</a>
      </div>
      <div class="card-footer text-muted">
        Posted on January 1, 2017 by
        <a href="#">xxx</a>
      </div>
    </div>
  </div>
</template>

所以我想访问我的帖子Home.vue并制作for循环..怎么做?谢谢指教!:)

<script>
// @ is an alias to /src
import HomeComponent from "@/components/HomeComponent.vue";

export default {
  name: "home",
  components: {
    HomeComponent
  },
};
</script>

标签: javascriptarraysvue.jsvuejs2

解决方案


您必须将数据作为道具传递给 Home 组件。更多信息可以在这里找到。但这里有一个快速解决您的问题的方法。

比较

<template>
  <!-- Blog Entries Column -->
  <div class="col-md-8">
    <h1 class="my-4">Статии</h1>

    <!-- Blog Post -->
    <div class="card mb-4" v-for="post in posts">
      <div class="card-body">
        <h2 class="card-title">{{ post.title }}</h2>
        <p class="card-text">{{ post.body }}</p>
        <a href="#" class="btn btn-primary">Read More &rarr;</a>
      </div>
      <div class="card-footer text-muted">
        Posted on January 1, 2017 by
        <a href="#">xxx</a>
      </div>
    </div>
  </div>
</template>

<script>
 export default {
   props:['posts']
 }
</script>

主页.vue

<template>
  <comp :posts="posts"></comp>
</template>

<script>
import Comp from './components/Comp.vue'
export default {
  name: "HomeComponent",
  components: {
    'comp': Comp
  },
  data() {
    posts: [
      { title: "Hello", body: "Some text" },
      { title: "Hello", body: "Some text" },
      { title: "Hello", body: "Some text" },
      { title: "Hello", body: "Some text" }
    ];
  }
};
</script>

推荐阅读