diceline-chartmagnifiermouse-upquestion-marktwitter-whiteTwitter_Logo_Blue

Today I Learned

Customize web page using query parameters with help of $route.query

VueJS offers the possibility to access query parameters so that you can customise a certain's page content based on the given parameters.

For instance, we have the following method and the following query parameters:

https://*link*?message=Custom+Message
    getQuery() {
      if (this.$route.query.message) {
        this.queryMessage = this.$route.query.message
      }
    },

This method will set a variable according to the query parameter "message", that can be further used in the content of the page. For example in a heading:

    <h1>{{ queryMessage }}</h1>

Also, by using the functionality of $router combined with "v-if", the user can render components conditionally.

    getQuery() {
      if (this.$route.query.icon) {
        this.queryIcon = this.$route.query.icon === 'true'
      }
    },
    <svg v-if="queryIcon">

Therefore, when parsing a query containing:

?icon=true

only then, the svg will be rendered.

How to access refs outside a VueJs template

Sometimes you need to make use of the ref attribute to access a child component in VueJs, like so:

<input ref="someRefName"></input>
this.$refs.someRefName

But what if you need to do the same thing for an html element that's still inside your app but outside of your VueJs template or component? Maybe you've tried it and this.$refs.someRefName comes in undefined.

That's when the $root instance comes in handy. Just add the ref attribute on the target element and access it in your VueJs component like this:

this.$root.$refs.someRefName

That makes VueJs look for that reference in the root instance of your app, and not only inside your component.

Just make sure you don't overuse it. Most of the times, there's a better way to do what you need to do.