How make json data available for my Vue dynamic routes

筅森魡賤 提交于 2020-07-04 00:19:28

问题


I have a List component where I fetch my date from db/blogs.json:

created() {
    fetch('http://localhost:3000/blogs')
    .then(response => {
      return response.json();
    })
    .then(data => {
      this.blogs = data;
    })
  },

In my BlogDetail.vue I have:

<script>
export default {
  data: () => {
    return {  
      blogId:this.$route.params.id
    }
  },
  computed: {
    blog() {
      return this.blogs.find(
        blog => blog.id === this.blogId
      )
    }
  }
}
</script>

But how do I get the blogs data in this component, which I fetched in the List component?

Because now in the <template> section of my BlogDetail.vue I cannot access e.g. {{ blog.name }}

Update:

I try passing blogs with props:

Now I am accepting a prop in BlogDetails.vue:

props: {
    blogs: {
      type: Array
    }
  },

But from where (which component), I have to registering the prop like :blogs="blogs"?

Update 2:

This is what I have so far, link to the sandbox


回答1:


Here is the working sandbox.

Firstly you need to import JSON data from your JSON file correctly. As:

<script>
import ListItem from "./ListItem";
import Blogs from "../../public/db/blogs.json";

export default {
  name: "List",
  components: {
    ListItem
  },
  data() {
    return {
      blogs: Blogs.experiences
    };
  },
  created() {}
};
</script>

Have to send props in the router-link as :

<router-link 
  :to="{ name: 'BlogDetails', params: { id: blog.id,blog:blog }}">More information
</router-link>



回答2:


You can send props to the child component in the tag name, in your case:

  //LIST component(PARENT)
  <tamplate>
    <BlogDetail :blogs="blogs"></BlogDetail> //CHILD component
  </template>


来源:https://stackoverflow.com/questions/62482212/how-make-json-data-available-for-my-vue-dynamic-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!