Categories
Vue Answers

How to Get an Element within a Component with Vue.js?

Sometimes, we want to get an element within a component with Vue.js.

In this article, we’ll look at how to get an element within a component with Vue.js.

Get an Element within a Component with Vue.js

To get an element within a component with Vue.js, we can assign a ref to the element we want to get.

Then we can get the element with the this.$refs property in any lifecycle or regular methods.

For instance, we can write:

<template>
  <div id="app">
    <span ref="someName" class="foo bar">Child Span</span>
  </div>
</template>

<script>
export default {
  name: "App",
  mounted() {
    const childSpanClassAttr = this.$refs.someName.getAttribute("class");
    console.log(childSpanClassAttr);
  },
};
</script>

We set the ref attribute of the span to someName .

Then we can the span by writing this.$refs.someName in any lifecycle or regular methods.

And we can call any DOM element method like getAttribute on it.

We get the value of the class attribute with 'class' as the argument of getAttribute .

Therefore, the console log logs 'foo bar’ .

Conclusion

To get an element within a component with Vue.js, we can assign a ref to the element we want to get.

Then we can get the element with the this.$refs property in any lifecycle or regular methods.

Categories
Vue Answers

How to Detect Clicks Outside an Element with Vue.js?

Sometimes, we want to detect clicks outside an element with Vue.js.

In this article, we’ll look at how to detect clicks outside an element with Vue.js.

Detect Clicks Outside an Element with Vue.js

We can detect clicks outside an element with Vue.js by creating our own directive.

For instance, we can write:

<template>
  <div id="app" style="width: 500px; height: 500px">
    <div v-click-outside="onClickOutside">hello world</div>
  </div>
</template>

<script>
import Vue from "vue";

Vue.directive("click-outside", {
  bind(el, binding, vnode) {
    el.clickOutsideEvent = (event) => {
      if (!(el === event.target || el.contains(event.target))) {
        vnode.context[binding.expression](event);
      }
    };
    document.body.addEventListener("click", el.clickOutsideEvent);
  },
  unbind(el) {
    document.body.removeEventListener("click", el.clickOutsideEvent);
  },
});

export default {
  name: "App",
  methods: {
    onClickOutside() {
      console.log("clicked outside");
    },
  },
};
</script>

We call Vue.directive with the directive name and an object that has the bind and unbind methods to add the el.clickOutsideEvent method in the bind method.

In clickOutsideEvent , we check if el isn’t event.target and that it doesn’t contain event.target .

If both are true , then we add vnode.context[binding.expression](event); to run the method that we set as the value of the v-click-outside directive.

Then we call document.body.addEventListener to add a click event listener to run clickOutsideEvent .

In the unbind method, we remove the event listener with removeEventListener when we unbind the directive.

Then in the template, we add v-click-outside and set the value of it to onClickOutside to run the method when we click outside.

When we click outside, we should see 'clicked outside' logged.

Conclusion

We can detect clicks outside an element with Vue.js by creating our own directive.

Categories
Vue Answers

How to Reload a Route with Vue Router?

Sometimes, we want to reload a route created with Vue Router.

In this article, we’ll look at how to reload a route created with Vue Router.

Reload Route with Vue Router

To reload a route with Vue Route, we can call the this.$router.go() method.

If it has no arguments, then it’ll reload the current route.

We can also add an unique value for the key prop to the router view:

<router-view :key="$route.fullPath"></router-view>

This way, it’ll notice when the path changes and it’ll trigger a reload of the component with new data.

Conclusion

To reload a route with Vue Route, we can call the this.$router.go() method.

If it has no arguments, then it’ll reload the current route.

Categories
Vue Answers

How to Pass Multiple Parameters to a Vuex Mutation?

Sometimes, we want to pass multiple parameters to a Vuex mutation.

In this article, we’ll look at how to pass multiple parameters to a Vuex mutation.

Passing Multiple Parameters to a Mutation with Vuex

To pass multiple parameters to action with Vuex, we can pass in an object as the payload.

For instance, we can create our mutation by writing:

mutations: {
  setToken(state, { token, expiration }) {
    localStorage.setItem('token', token);
    localStorage.setItem('expiration', expiration);
  }
}

We have an object as the second parameter.

It has the token and expiration properties.

Then we can invoke the mutation by writing:

store.commit('setToken', {
  token,
  expiration,
});

We invoke the setToken mutation with the token and expiration properties in an object as the 2nd argument.

Conclusion

To pass multiple parameters to action with Vuex, we can pass in an object as the payload.

Categories
Vue Answers

How to Get Query Parameters from a URL in Vue.js and Vue Router?

Sometimes, we want to get query parameters from a URL with Vue.js and Vue Router.

In this article, we’ll look at how to get query parameters from a URL with Vue.js and Vue Router.

Get Query Parameters from a URL in Vue.js

We can get the query parameters from a URL in Vue with the this.$route.query property.

To get the query parameter foo=bar , we write:

this.$route.query.foo

and we get 'bar' as the value.

This is available assuming we’re using Vue Router in our Vue app.

If we haven’t added it, we can write:

index.html

<script src="https://unpkg.com/vue-router"></script>

index.js

const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/page',
      name: 'page',
      component: PageComponent
    }
  ]
});

const vm = new Vue({
  router,
  el: '#app',
  mounted() {
    const q = this.$route.query.q;
    console.log(q)
  },
});

to get it.

We create the VueRouter instance and pass it into the object we passed into the Vue constructor.

routes has the routes.

Conclusion

We can get the query parameters from a URL in Vue with the this.$route.query property.