JuniorDev
JuniorDev

Reputation: 162

VueJs use props that comes from <router-link>

i have a navbar and there is a text field in that the user can search for posts by tags. If the user enters 1-3 tags, the written tags will be stored in a tags array.

My router-link in the navbar component looks like this: (only relevant part)

<router-link :to="{name:'posts', props:{searchTags: tags}}">
         <button type="button" v-if="this.tags.length > 0"
               class="...">Search
         </button>
</router-link>

in my routes.js is my posts route (important snippet of my routes.js)

 routes: [
        {
            path: "/posts",
            component: posts,
            name: 'posts'
        },
    ]

The navbar should send the tags array to the posts component. Unfortunately I can't do it.

The posts component, sends a post request to an API that gets the latest posts. But I want that when tags are passed, not the newest posts are fetched, only posts with certain tags. But first I have to get the tags somehow.

I tried to get them with "this.$props.searchTags" and other things. Unfortunately the result is always "undefined".

export default {
        name: "posts",
        props: {
           searchTags: Array,
           required: false
        },
        data: function () {
            return {
                apiUrl: '/getPosts',
                ....              
                tags: [this.searchTags],
            }
        },
        methods: {
            getPosts: function (url) {
                this.$http.get(url).then(function (data) {
                       // blabla                           
                });
            },
            getPostsByTags: function() {                
                      //
            }, 
        },
        created() {
            if(this.$props.searchTags == null)
                  this.getPosts(this.apiUrl);
            else 
                  this.getPostsByTags(bla);
        },
    }

Upvotes: 2

Views: 7085

Answers (2)

grouchoboy
grouchoboy

Reputation: 1024

Try to add props: true in your route definition

routes: [
    {
        path: "/posts",
        component: posts,
        name: 'posts',
        props: true
    },
]

Upvotes: 2

aBiscuit
aBiscuit

Reputation: 4732

Router link to property accepts string or Location as a value. Location object does not have props property.
Instead, it is possible to use params to send data to route component:

<router-link 
  :to="{ name: 'posts', params: { searchTags: tags } }"
>
...
</router-link>

This way searchTags with value of assigned tags will be accessible via this.$route.params.searchTags inside destination component.

So created hook of example above should be updated to:

created () {
  if (!this.$route.params.searchTags) {
    this.getPosts(this.apiUrl);
  } else {
    this.getPostsByTags(bla);
  }                  
},

Upvotes: 2

Related Questions