javascript - VueJS,将数据从组件传递到另一个组件

标签 javascript arrays vue.js vuejs2

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

我有一个名为 components/HomeComponent.vue

的组件

这里是:

HomeComponent.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>

我有我的“ View ”views/Home.vue

Home.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>

最佳答案

您必须将数据作为 props 传递给 Home 组件。更多信息可查询here 。但这里有一个快速解决您的问题的方法。

Comp.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>

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

HomePage.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>

关于javascript - VueJS,将数据从组件传递到另一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53998657/

相关文章:

python - numpy:在另一个表中查找所有出现的元素

javascript - 防止页面离开时弹出 "Confirm Navigation"对话框

javascript - 登录/注册 AWS Cognito React 中的安全页面

javascript - 在 React Native 中使用 ObjectiveC 库

node.js - 使用 Cypress ,我将如何编写一个简单的测试来检查页面上是否存在 Logo 图像

javascript - 我可以使用 vue-select 在多个字段中进行搜索吗?

javascript - Vue.js 如何上传图像并在之后运行自定义方法

javascript - JQuery Toggle Class 加号和减号图标问题

javascript - 加入数组中的元素并从数组中删除一些元素

Java - 数组输出 null