Categories
JavaScript Vue

Add a Numeric Input to a Vue App with vue-numeric

We can add a numeric input to our Vue app with the vue-numeric package.

We can install it by running:

npm install vue-numeric --save

Then we can register the plugin by writing the following in main.js:

import Vue from "vue";
import App from "./App.vue";
import VueNumeric from "vue-numeric";

Vue.use(VueNumeric);

Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount("#app");

to register the VueNumeric plugin globally.

Then we can write:

<template>
  <div id="app">
    <vue-numeric currency="$" separator="," v-model="price"></vue-numeric>
    <p>{{price}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      price: 0
    };
  }
};
</script>

We have the vue-numeric component.

It takes the currency prop to prepend a currency symbol to the input.

separator adds the separator to our input when it’s displayed.

v-model binds the inputted value to the price state.

The currency symbol and the separator are only displayed in the input when we move away from the input.

The value that’s set to price is still what we typed in, except when we type in something that’s not a whole number.

By default, it doesn’t let us enter decimals.

We can add the :precision prop to let us enter decimals.

There’s also the minus prop to let us enter negative numbers.

Also, the placeholder prop lets us add placeholders.

The output data type can be changed with output-type.

The empty-value prop lets us set a default value for the state.

So we can write:

<template>
  <div id="app">
    <vue-numeric currency="$" separator="," v-bind:precision="2" v-model="price"></vue-numeric>
    <p>{{price}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      price: 0
    };
  }
};
</script>

to allow up to 2 decimals to be entered.

The entered value will be converted automatically to the specified format when we move our focus away from the input.

The vue-numeric package lets us add a currency input easily.

It can be adjusted to use a different thousands separator, the numver of decimal digits, and more.

Categories
JavaScript Vue

Display a Toast in a Vue App with vue-toastr

A toast is a popup notification that has a black background color and disappears after a set time.

To add them easily to our Vue app, we can use the vue-toastr package.

To install it, we run:

npm install vue-toastr

Then we can register the plugin by writing:

import Vue from "vue";
import App from "./App.vue";
import VueToastr from "vue-toastr";
Vue.use(VueToastr);

Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount("#app");

Then in our component, we can display a toast by writing:

<template>
  <div id="app"></div>
</template>

<script>
export default {
  mounted() {
    this.$toastr.s("Success", "Success Toast Title");
  }
};
</script>

Display Toast

We display the toast after it’s loaded.

s is for success.

The first argument is the message and the 2nd is the title.

There are also other methods we can display toasts with:

this.$toastr.e("error");
this.$toastr.w("warning");
this.$toastr.i("information");

e is for error, w is for wanting, and i is for information.

Remove Toast

We can remove a toast with the removeByName, Close, or removeByTypeMethods.

For instance, we can create a toast by writing:

const toast = this.$toastr.Add({
  name: "name", 
  msg: "Hi", 
  type: "error"
});

And then write:

this.$toastr.Close(toast);

to close it.

We can also remove it by the name:

this.$toastr.removeByName("name");

The name is the value of the name property we have in the object we passed into Add.

Also, we can remove by type:

this.$toastr.removeByType("error");

We remove all toast with type error.

Options

In addition to name, type and msg, we can also pass in title to set the title.

classNames set the class names for the toast so we can style it.

timeout sets the amount of time before it’s closed.

closeOnHover makes the toast close on hover.

clickClose makes the toast close on click.

It also takes a few event handlers, including onCreated, onClosed, and onClicked, onMouseOver, and onMouseOut.

progressbar lets us enable or disable the progress bar.

And progressBarValue lets us change the initial value of the progress bar.

Conclusion

We can use vue-toastr to create very customizable toasts in our Vue.js apps.

We can change styles, timeouts, open and close toasts in various ways, and much more.

Categories
JavaScript Vue

Creating Masked Input in a Vue App with v-mask

We can use the v-mask package to add masked inputs into our Vue component.

To install it, we run:

npm install v-mask

Then we can use it by registering the plugin in main.js:

import Vue from "vue";
import App from "./App.vue";
import VueMask from "v-mask";
Vue.use(VueMask);

Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount("#app");

We called Vue.use(VueMask); to register the plugin globally.

Then we can add a mask to a component by writing:

<template>
  <div id="app">
    <input type="text" v-mask="'###-###-####'" v-model="phone">
    <p>{{phone}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      phone: ""
    };
  }
};
</script>

The v-mask directive is available after we registered the plugin/

We pass in a string with the phone number mask.

Now the input can only take phone numbers.

Also, we have v-model to bind the inputted value into a state.

Now when we type in a phone number, we’ll see it reflect in the p element below.

We can also use it as a filter.

If we have:

<template>
  <div id="app">
    <p>{{phone | VMask('(###) ###-####')}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      phone: "1234567890"
    };
  }
};
</script>

Then the value of phone will be displayed as a phone number.

We just pass in the mask format into the VMask filter to display the string our way.

v-mask is an easy to use plugin to let us add input masks into a Vue app.

It can also be used as a filter.

Categories
JavaScript Svelte

Changing HTML Class in Svelte Components with the Class Directive

Svelte is an up and coming front end framework for developing front end web apps.

It’s simple to use and lets us create results fast.

In this article, we’ll look at how to change class names dynamically with the Svelte class directive.

Class Directive

We can use the class directive with an expression to return the class to display based on the condition.

Also, we can add class names as modifiers and the condition to display it as the value as pass in.

For instance, we can write the following code to toggle a class:

App.svelte :

<script>  
let enableFoo;  
</script>

<style>  
  .foo {  
    color: red;  
  }  
</style>

<button    
  on:click="{() => enableFoo = !enableFoo}"  
>  
  Toggle Class  
</button>  

<p class="{enableFoo ? 'foo': ''}">foo</p>

In the code above, we have class=”{enableFoo ? ‘foo’: ‘’}” to toggle the foo class on when the enableFoo variable is true since we return 'foo' then. Otherwise, we have no class apply to the p element.

The class directive conditionally applies the foo class to the p element since we added the class directive to that element.

The button toggles the enableFoo on and off, which is used to return 'foo' when enableFoo is true . Otherwise, we return an empty string, which means no class.

The foo class sets the color to red. So the text in the p tag will be toggle between red and black.

We can also write the code to do the same thing as follows:

App.svelte :

<script>  
let enableFoo;  
</script>

<style>  
  .foo {  
    color: red;  
  }  
</style>

<button    
  on:click="{() => enableFoo = !enableFoo}"  
>  
  Toggle Class  
</button>  
<p class:foo="{enableFoo}">foo</p>

We changed:

class="{enableFoo ? 'foo': ''}"

to:

class:foo="{enableFoo}

foo is the class name, which the modifier for the class directive.

If our class is the same as our variable name for toggling on a class on and off, then we can shrink the class directive code with the shorthand.

For instance, instead of writing:

<script>  
let foo;  
</script>

<style>  
  .foo {  
    color: red;  
  }  
</style>

<button    
  on:click="{() => foo = !foo}"  
>  
  Toggle Class  
</button>  

<p class:foo="{foo}">foo</p>

We can write:

<script>  
let foo;  
</script>

<style>  
  .foo {  
    color: red;  
  }  
</style>

<button    
  on:click="{() => foo = !foo}"  
>  
  Toggle Class  
</button>  

<p class:foo>foo</p>

They both toggle the foo class. class:foo=”{foo}” is the same as class:foo .

Conclusion

The class directive lets us conditionally apply a class to an element. We can do that either by passing in an expression to conditionally return a class name to apply.

Or we can add the class name as the modifier to the class directive and then pass in the condition to add the class as the value we pass into the directive.

Categories
JavaScript Svelte

Passing Props Between Svelte Components

Svelte is an up and coming front end framework for developing front end web apps.

It’s simple to use and lets us create results fast.

In this article, we’ll look at how to pass data to child Svelte components via props.

Props

We can use the export keyword to create a variable that can be passed into a child within the child component itself.

For example, if App.svelte is the parent and Button.svelte is the child, then we can write the following to pass a value to the text prop of Button:

App.svelte :

<script>  
import Button from "./Button.svelte";  
</script>

<main>  
  <Button text='Toggle' />  
</main>

Button.svelte :

<script>  
export let text;  
</script>

<button>  
  {text}  
</button>

In the code above, we wrote:

export let text;

to indicate that Button takes text as a prop.

Then in App.svelte , we write:

<Button text='Toggle' />

to pass in the string 'Toggle' to Button . Since Button references text between the button tags, we see the word Toggle as the text for the button.

We can set default values of props by setting the value of our export expression as follows:

App.svelte :

<script>  
import Button from "./Button.svelte";  
</script>

<main>  
  <Button text='Toggle' />  
  <Button />  
</main>

Button.svelte :

<script>  
export let text = "Empty Button";  
</script>

<button>  
  {text}  
</button>

In the code above, we set text to 'Empty Button' in Button.svelte .

Therefore, when we have a Button without a text prop passed in, we’ll get that value as the text of the button.

Spread Props

We can use the spread operator to spread an object’s properties into multiple props.

For instance, if we want to pass in more than one prop, we can write the following:

App.svelte ;

<script>  
  import Info from "./Info.svelte"; 
  const person = {  
    name: "Jane Smith",  
    age: 20,  
    gender: "female"  
  };  
</script>

<main>  
  <Info {...person} />  
</main>

Info.svelte :

<script>  
  export let name;  
  export let age;  
  export let gender;  
</script>

<p>{name} {age} {gender}</p>

In the code above, we have the person object in App.svelte , which spread into the name , age , and gender props via the spread operator.

In Info.svelte , we indicated that name , age , and gender are props. Since they’re passed in from App.svelte , the values will be displayed in the p tag.

So we have Jane Smith 20 female on the screen.

Conversely, if we want to access props that aren’t declared explicitly with export , we can get the values by the $$props variable.

For instance, we can rewrite the example above as:

App.svelte :

<script>  
  import Info from "./Info.svelte"; 
  const person = {  
    name: "Jane Smith",  
    age: 20,  
    gender: "female"  
  };  
</script>

<main>  
  <Info {...person} />  
</main>

Info.svelte :

<p>{$$props.name} {$$props.age} {$$props.gender}</p>

As we can see, we removed all the exports in Info.svelte and just referenced $$props directly in our template markup.

Conclusion

We can pass data from a parent component to a child component by declaring props withexport expressions.

Then we can pass in props from the parent to the child.

If we have lots of props that we want to pass in, we can use the spread operator to spread object properties as props.

Finally, we can use the $$props variable to reference the props that have no export expressions associated with them.