1

I'm trying to wrap my head around Vue - in particular, passing data from the Vue instance to a component. I'm also using Vue-Router and Axios, and it's (meant to be) a pretty simple project, with just one JavaScript file.

The important parts of index.html look like this:

<div id="app">

    <!-- Navigation -->
    <ul>
        <router-link tag="li" to="/" exact><a>Home</a></router-link>
        <router-link tag="li" to="/category"><a>Category</a></router-link>
    </ul>

    <!-- The Content -->
    <router-view></router-view>

</div>

Then in main.js, there is the following:

var VideoList = Vue.component('video-list', {
    props: ['posts'],
    template: '<ul> <li v-for="post in posts"> {{post.id}} </li> </ul>'
});

var router = new VueRouter({
    mode: 'history',
    linkActiveClass: 'active',
    routes: [
        { path: '/', component: VideoList},
        { path: '/category', component: VideoList }
    ]
});

new Vue({
    el: '#app',
    data: {
        posts: []
    },
    router: router,
    created: function() {
        var me = this;
        axios.get( '/wp-json/wp/v2/posts' )
            .then( function(response){
                me.posts = response.data;
            })
        }
});

The data loads from the AJAX call (I can log it etc), and exists on the Vue instance when I look at it with the Vue devtools add-on. I just can't quite figure out how to pass the data on to the <video-list> component. At the moment I'm getting an error: The data property "posts" is already declared as a prop. Use prop default value instead.

verism
  • 1,106
  • 1
  • 12
  • 35
  • https://router.vuejs.org/en/essentials/passing-props.html – Roy J Apr 16 '17 at 13:48
  • @RoyJ thanks, but - unless I'm mistaken - this article seems to address passing route wildcards or query strings. – verism Apr 16 '17 at 13:56
  • That's what it looks like, but more generally, you can pass props to the router, and it will pass them on to components. http://stackoverflow.com/questions/37937262/passing-props-to-vue-js-components-instantiated-by-vue-router – Roy J Apr 16 '17 at 17:35

2 Answers2

1

You would pass props to the router-view, just like you would to any other component.

<router-view :posts="posts" ></router-view>

VideoList should then have access to posts.

Eric Guan
  • 15,474
  • 8
  • 50
  • 61
0

Not quite the solution I wanted, but this seems to have done the trick. Putting the data directly onto the component turned out to work in this particular case.

var VideoList = Vue.component('video-list', {
    template: '<ul><li v-for="post in posts"><video-post></video-post></li></ul>',
    data: function() {
        return {
            posts: []
        }
    },
    mounted: function() {
        var me = this;
        axios.get( '/wp-json/wp/v2/posts' )
            .then( function(response){
                me.posts = response.data;
            })
    }
})
verism
  • 1,106
  • 1
  • 12
  • 35