Categories
Vue Answers

How to Watch Multiple Properties with a Single Handler in Vue.js?

Sometimes, we want to watch multiple properties with a single handler in Vue.js.

In this article, we’ll look at how to watch multiple properties with a single handler in Vue.js.

Watch Multiple Properties with a Single Handler in Vue.js

We can watch multiple properties with a single handler in Vue.js with the this.$watch method.

For instance, we can write:

<template>
  <div id="app"></div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      name: "jane",
      surname: "smith",
    };
  },
  mounted() {
    this.$watch(
      (vm) => [vm.name, vm.surname],
      (val) => {
        const fullName = this.name + " " + this.surname;
        console.log(fullName);
      },
      {
        immediate: true,
        deep: true,
      }
    );
  },
};
</script>

We name the name and surname reactive properties which we want to watch the values for.

And we do that by calling this.$watcg in the mounted hook with a function that returns an array with the reactive properties we want to watch.

vm is the component instance.

We get the values in function in the 2nd argument and we do what we want to it.

The 3rd argument is an object with some options.

immediate set to true means we watch the initial value of the reactive properties.

deep set to true means we watch for changes of properties in all levels of an object.

Conclusion

We can watch multiple properties with a single handler in Vue.js with the this.$watch method.

Categories
Vue Answers

How to Auto-Reload or Refresh Data with a Timer in Vue.js?

Sometimes, we want to auto-reload or refresh data with a timer in Vue.js.

In this article, we’ll look at how to auto-reload or refresh data with a timer in Vue.js.

Auto-Reload or Refresh Data with a Timer in Vue.js

To auto-reload or refresh data with a timer in Vue.js, we can use the setInterval method.

For instance, we can write:

<template>  
  <div id="app">  
    {{ answer }}  
  </div>  
</template>  
<script>  
export default {  
  name: "App",  
  data() {  
    return {  
      answer: {},  
      timer: "",  
    };  
  },  
  created() {  
    this.fetchData();  
    this.timer = setInterval(this.fetchData, 5000);  
  },  
  methods: {  
    async fetchData() {  
      const res = await fetch("https://yesno.wtf/api");  
      const data = await res.json();  
      this.answer = data;  
    },  
    cancelAutoUpdate() {  
      clearInterval(this.timer);  
    },  
  },  
  beforeDestroy() {  
    this.cancelAutoUpdate();  
  },  
};  
</script>

We have the fetchData method that gets data from an API.

And we create the timer with the setInterval in the created hook.

We also call fetchData to get the initial data.

We pass in this.fetchData to run it periodically.

And we specify the period to be 5000 milliseconds.

In the besforeDestroy hook, we call cancelAutoUpdate to call clearInterval to clear the timer so that the timer is removed when we unmount the component so it’ll stop running.

In the template, we render the answer .

Conclusion

To auto-reload or refresh data with a timer in Vue.js, we can use the setInterval method.

Categories
Vue Answers

How to Check for the Last Property of an Object in a v-for Loop?

Sometimes, we want to check for the last property of an object in a v-for loop.

In this article, we’ll look at how to check for the last property of an object in a v-for loop.

Check for the Last Property of an Object in a v-for Loop

We can check for the last property of an object in a v-for loop with the index property with the index loop variable.

For instance, we can write:

<template>  
  <div id="app">  
    <p v-for="(val, key, index) of person" :key="key">  
      key: {{ key }}, val: {{ val }}, index: {{ index }}  
      <span v-if="index !== Object.keys(person).length - 1">, </span>  
    </p>  
  </div>  
</template>  
<script>  
export default {  
  name: "App",  
  data() {  
    return {  
      person: { name: "Joe", age: 35, department: "IT" },  
    };  
  },  
};  
</script>

We get the property value with val .

And we get the property name with key .

The index has the index of the property being looped through.

We get the number of properties in person with Object.keys(person).length .

So we subtract that by 1 to get the index of the last property in person .

Conclusion

We can check for the last property of an object in a v-for loop with the index property with the index loop variable.

Categories
Vue Answers

How to Trigger Events on an Element Using Vue.js?

Sometimes, we want to trigger events on an element with Vue.js.

In this article, we’ll look at how to trigger events on an element with Vue.js.

Trigger Events on an Element Using Vue.js

We can trigger events on an element with Vue.js by assigning a ref to the element we want to trigger events for.

Then we can call methods on the element assigned to the ref to trigger the event.

For instance, we can write:

<template>  
  <div id="app">  
    <button type="button" @click="myClickEvent">Click Me!</button>  
    <button type="button" @click="myClickEvent2" ref="myBtn">  
      Click Me 2!  
    </button>  
  </div>  
</template>  
<script>  
export default {  
  name: "App",  
  methods: {  
    myClickEvent($event) {  
      const elem = this.$refs.myBtn;  
      elem.click();  
    },  
    myClickEvent2() {  
      console.log("clicked");  
    },  
  },  
};  
</script>

We have 2 buttons. And we want to trigger the click event on the 2nd button.

To do that, we add the myClickEvent method which gets the button that’s assigned to the myBtn ref.

And then we call click on it.

In the 2nd button, we set the @click directive to myClickEvent2 to log the click.

Now when we click on the first button, we see 'clicked' logged.

Conclusion

We can trigger events on an element with Vue.js by assigning a ref to the element we want to trigger events for.

Categories
Vue Answers

How to Filter Text Input to Only Accept Numbers and a Dot with Vue.js?

Sometimes, we want to filter text input to only accept numbers and a dot with Vue.js.

In this article, we’ll look at how to filter text input to only accept numbers and a dot with Vue.js.

Filter Text Input to Only Accept Numbers and a Dot with Vue.js

We can filter text input to only accept numbers and a dot with Vue.js by checking for keycodes which aren’t numbers and preventing the default action in those case.

The default action would be to accept the input.

For example, we can write:

<template>  
  <div id="app">  
    <input v-model="num" @keypress="isNumber($event)" />  
  </div>  
</template>  
<script>  
export default {  
  name: "App",  
  data() {  
    return {  
      num: 0,  
    };  
  },  
  methods: {  
    isNumber(evt) {  
      const charCode = evt.which ? evt.which : evt.keyCode;  
      if (  
        charCode > 31 &&  
        (charCode < 48 || charCode > 57) &&  
        charCode !== 46  
      ) {  
        evt.preventDefault();  
      }  
    },  
  },  
};  
</script>

to add a number input and the isNumber method which we set as the value of the @keypress directive to check the keys that are pressed.

We get the keyboard key character code from the evt.which or evt.keyCode property.

Then we check if the charCode is the ones listed in the condition in the if statement.

If they match, then we call evt.preventDefault to stop the default action, which is to accept the inputted value.

Conclusion

We can filter text input to only accept numbers and a dot with Vue.js by checking for keycodes which aren’t numbers and preventing the default action in those case.