Categories
JavaScript Basics

Highlights of JavaScript — Date, Time, and Functions

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Change Date and Time

The Date instance lets us change various parts of the date and time.

setFullYear lets us set the year of a Date instance.

setMonth lets us set the month of a Date instance. It accepts a number from 0 to 11, with 0 being January and 11 being December.

setDate lets us set the day of the month.

setHours lets us set the minutes past an hour.

setSeconds lets us set the seconds past the minute.

And setMilliseconds lets us set the milliseconds past the second.

For example, we can call setFullYear by writing:

let d = new Date();
d.setFullYear(2040);

or:

let d = new Date();
d.setMonth(11);

The rest can be called the same way.

Functions

Functions are blocks of code that we can use repeatedly to do what we want.

We called functions before with setFullYear , setMonth , etc.

They may take 0 or more arguments.

For example, we can create our own tellTime function by writing:

function tellTime() {
  let now = new Date();
  let jr = now.getHours();
  let min = now.getMinutes();
  alert(`${hr}:${min}`);
}

We called getHours to get the hours and getMinutes to get the minutes.

Pass Data to Functions

Functions can have parameters so we can pass data to them.

For example, we can write:

function greetUser(greeting) {
  alert(greeting);
}

The greetUser method accepts the greeting parameter, and we use the value as the argument for the alert function.

This way, we can specify the message for the alert.

We can call our function by writing:

greetUser('hello james');

Now we should see an alert with the ‘hello james’ text displayed.

We can separate multiple parameters and arguments with commas. For example, we can write:

function showMessage(greeting, name) {
  alert(`${greeting}, ${name}`);
}

The showMessage function has the greeting and name parameters.

Then we can call showMessage by writing:

showMessage('hello', 'mary');

With parameters, we can customize how functions can be called.

Return Data in Functions

If we want to get the data computed by functions, then we add the return statement to return the data we want from the function.

For example, we can write:

function getTotal(subtTotal, taxRate) {
  return subTotal * (1 + taxRate);
}

We created the getTotal function that takes the subTotal and taxRate parameters.

Then we return the computed result by using the return statement.

We can call the getTotal function by writing:

const total = getTotal(100, 0.05);

We pass in the numbers for the subTotal and taxRate and assign the returned value to total .

Therefore, total is 105.

Conclusion

We can change the date and time with Date instance methods.

Also, we can create functions with parameters and return data in it so we can use that result somewhere else.

Categories
JavaScript Basics

Highlights of JavaScript — Dates and Rounding

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Controlling the Length of Decimals

We can control the length of decimals by using the toFixed method.

For example, if we have:

let total = (8.8888).toFixed(2);

Then total is '8.89' . toFixed takes the number of digits to round to and returns string with the rounded number.

If the decimal ends with a 5, it usually rounded up.

But some browsers kay round down.

Get the Current Date and Time

To get the current date and time, we can create a new Date instance with new Date() .

Then we can convert the Date instance to a string by writing:

let now = new Date();
let dateString = now.toString();

To get the day of the week, we call the getDay method:

let now = new Date();
let day = now.getDay();

It returns a number from 0 to 6, with 0 being Sunday, and 6 being Saturday.

If we want to show a more human-readable date, we can write:

let dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
let now = new Date();
let day = now.getDay();
let dayName = dayNames[day];

We can use day as the index of dayNames to get the English version of the day of the week.

Extracting Parts of Date and Time

The Date instance comes with various methods to get various parts of a date and time.

getMonth returns the month of the date from 0 to 11, with 0 being January and 11 being December.

getDate gives us the number for the dat of the month.

getFullYear returns the 4 digit version of the year.

getHours gives us a number from 0 to 23, which corresponds to midnight and 11pm.

getMinutes returns the minutes of the hour from 0 to 59.

getSeconds returns the seconds of the minute from 0 to 59.

And getMilliseconds returns a number from 0 to 999.

getTime gives us the number of milliseconds that have elapsed since Jan 1, 1970 midnight UTC.

We can call them all from a date instance. For example, we can write:

let now = new Date();
let day = now.`getMilliseconds`();

Specify Date and Time

We can specify date and time with the Date constructor.

To return the current date and time, we write:

let today = new Date();

And we can calculate the number of days difference by subtracting the timestamp between 2 dates:

let msToday = new Date().getTime();
let msAnotherDay = new Date(2029, 1, 1).getTime()
let msDiff = msAnotherDay - msToday;

Then to get the number of days difference, we can write:

let daysDiff = msDiff / (1000 * 60 * 60 * 24);

If we want to return the round the days to a whole number, we round down with Math.floor :

daysDiff = Math.floor(daysDiff);

Conclusion

We can calculate the difference between days with the timestamps.

Also, we can round numbers to a given number of decimal places with toFixed .

Categories
Vue

Storing Vue App Data in Session Storage with vue-sessionstorage

We can use the vue-sessionstorage library to store Vue app data in session storage of our browser.

In this article, we’ll look at how to use it to save data.

Installation

We can install the library by running:

npm i vue-sessionstorage

Save Data in Local Storage

After installing the library, we can save data in local storage with by writing:

main.js

import Vue from "vue";
import App from "./App.vue";
import VueSessionStorage from "vue-sessionstorage";
Vue.use(VueSessionStorage);
Vue.config.productionTip = false;

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

App.vue

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

<script>
export default {
  name: "App",
  mounted() {
    this.$session.set("username", "user123");
  }
};
</script>

We just register the plugin in main.js .

Then we have the this.$session object available for us to use anywhere.

We call set with the key and value of the data we want to save to save it.

To get the data, we can use the this.$session.get method:

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

<script>
export default {
  name: "App",
  mounted() {
    this.$session.set("username", "user123");
    console.log(this.$session.get("username"));
  }
};
</script>

The this.$session.exists method checks if a key exists:

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

<script>
export default {
  name: "App",
  mounted() {
    this.$session.set("username", "user123");
    console.log(this.$session.exists("username"));
  }
};
</script>

The this.$session.remove method removes the item with the given key:

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

<script>
export default {
  name: "App",
  mounted() {
    this.$session.set("username", "user123");
    console.log(this.$session.remove("username"));
  }
};
</script>

The this.$session.clear method clears session storage data with the given key:

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

<script>
export default {
  name: "App",
  mounted() {
    this.$session.set("username", "user123");
    console.log(this.$session.clear("username"));
  }
};
</script>

With session storage, different instances of the same app can store different data in their own session.

The data can be set both per-origin and per-instance, which is per-window or per-tab.

So the clear method will clear all data with the given key.

Conclusion

We can use the vue-sessionstorage library to save data to session storage.

Categories
Vue

Storing Data with Local Storage and Vuex with the vuex-persistedstate Library

The vuex-persistedstate library lets us add persistence to local storage of our data in our Vuex store.

In this article, we’ll look at how to use it to save data.

Installation

We can install it by running:

npm install --save vuex-persistedstate

Also, we can install it with a script tag:

<script src="https://unpkg.com/vuex-persistedstate/dist/vuex-persistedstate.umd.js"></script>

Then the window.createPersistedState is available for us to use.

Saving Vuex State in Local Storage

We can save our Vuex state to local storage with the createPersistedState function.

To use it, we write:

main.js

import Vue from "vue";
import App from "./App.vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);
Vue.config.productionTip = false;

const store = new Vuex.Store({
  state: {
    count: 0
  },
  plugins: [createPersistedState()],
  mutations: {
    increment: (state) => state.count++,
    decrement: (state) => state.count--
  }
});
new Vue({
  store,
  render: (h) => h(App)
}).$mount("#app");

App.vue

<template>
  <div id="app">
    <p>{{ count }}</p>
    <p>
      <button [@click](http://twitter.com/click "Twitter profile for @click")="increment">increment</button>
      <button [@click](http://twitter.com/click "Twitter profile for @click")="decrement">decrement</button>
    </p>
  </div>
</template>

<script>
export default {
  name: "App",
  computed: {
    count() {
      return this.$store.state.count;
    }
  },
  methods: {
    increment() {
      this.$store.commit("increment");
    },
    decrement() {
      this.$store.commit("decrement");
    }
  }
};
</script>

In main.js , we registered the Vuex plugin and created the store.

The store has the count state and mutations to change it,.

Also, we added the plugin created by the createPersistedState function from the vuex-persistedstate library.

This way, we can store the store’s state in local storage.

In App.vue , we get the count state in count computed property.

And we call commit to commit the mutations for changing the count state.

Storing Vuex State as Cookies

Alternatively, we can store Vuex states as cookies. To do that, we can use vuex-persistedstate with the js-cookie library.

We install js-cookie by running:

npm i js-cookie

In main.js , we change it to:

import Vue from "vue";
import App from "./App.vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";
import Cookies from "js-cookie";

Vue.use(Vuex);
Vue.config.productionTip = false;

const store = new Vuex.Store({
  state: {
    count: 0
  },
  plugins: [
    createPersistedState({
      storage: {
        getItem: (key) => Cookies.get(key),
        setItem: (key, value) =>
          Cookies.set(key, value, { expires: 3, secure: true }),
        removeItem: (key) => Cookies.remove(key)
      }
    })
  ],
  mutations: {
    increment: (state) => state.count++,
    decrement: (state) => state.count--
  }
});
new Vue({
  store,
  render: (h) => h(App)
}).$mount("#app");

App.vue stays the same.

We passed in an object so that we can get the data by its key with getItem .

setItem sets the data with the given key. expires is the expiry time in days. secure makes sure the cookie is only set over HTTPS.

removeItem removes an item by its key.

Secure Local Storage

We can scramble the data in local storage with the secure-ls library.

To use it, we can change main.js to:

import Vue from "vue";
import App from "./App.vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";
import SecureLS from "secure-ls";
const ls = new SecureLS({ isCompression: false });
Vue.use(Vuex);
Vue.config.productionTip = false;

const store = new Vuex.Store({
  state: {
    count: 0
  },
  plugins: [
    createPersistedState({
      storage: {
        getItem: (key) => ls.get(key),
        setItem: (key, value) => ls.set(key, value),
        removeItem: (key) => ls.remove(key)
      }
    })
  ],
  mutations: {
    increment: (state) => state.count++,
    decrement: (state) => state.count--
  }
});
new Vue({
  store,
  render: (h) => h(App)
}).$mount("#app");

We import the secure-ls library and create the ls object to let us get, set, and remove items from local storage.

Whatever is saved will be scrambled so no one can see it the browser dev console.

Conclusion

The vuex-persistedstate library is a useful library for storing Vuex state in local storage.

This way, we can keep the after we refresh the page.

Categories
Buefy

Buefy — Tags and Tooltips

Buefy is a UI framework that’s based on Bulma.

In this article, we’ll look at how to use Buefy in our Vue app.

Tag List

We add a list of tags with the b-taglist component.

To add it, we write:

<template>
  <div id="app">
    <b-taglist>
      <b-tag type="is-info">First</b-tag>
      <b-tag type="is-info">Second</b-tag>
      <b-tag type="is-info">Third</b-tag>
    </b-taglist>
  </div>
</template>

<script>
export default {
  name: "App"
};
</script>

We just put all the b-tag components inside.

The attached prop will attach 2 tags together:

<template>
  <div id="app">
    <b-taglist attached>
      <b-tag type="is-dark">npm</b-tag>
      <b-tag type="is-info">6</b-tag>
    </b-taglist>
  </div>
</template>

<script>
export default {
  name: "App"
};
</script>

Also, we can combine fields to group attached tags:

<template>
  <div id="app">
    <b-field grouped group-multiline>
      <div class="control">
        <b-tag type="is-primary" attached closable>Technology</b-tag>
      </div>
      <div class="control">
        <b-tag type="is-primary" attached closable>Vuejs</b-tag>
      </div>
      <div class="control">
        <b-tag type="is-primary" attached closable>CSS</b-tag>
      </div>
    </b-field>
  </div>
</template>

<script>
export default {
  name: "App"
};
</script>

We put them all in the b-field component with the grouped and grouped-multiline props to group them together.

Sizes and Types

We can change the color with the type prop:

<template>
  <div id="app">
    <b-tag type="is-info">Technology</b-tag>
  </div>
</template>

<script>
export default {
  name: "App"
};
</script>

And we can change the size with the size prop:

<template>
  <div id="app">
    <b-tag size="is-large">Technology</b-tag>
  </div>
</template>

<script>
export default {
  name: "App"
};
</script>

Toast

We can add toasts to display notifications.

For example, we can write:

<template>
  <div id="app">
    <button class="button is-medium" @click="toast">Launch toast</button>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    toast() {
      this.$buefy.toast.open("toast");
    }
  }
};
</script>

We called the this.$buefy.toast.open method to display a toast with the text in the argument.

Also, we can set the background color with the type property. message has the message.

We can also change the duration that it’s displayed and its position with the duration and position properties:

<template>
  <div id="app">
    <button class="button is-medium" @click="toast">Launch toast</button>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    toast() {
      this.$buefy.toast.open({
        duration: 5000,
        message: `Something's <b>not good</b>`,
        position: "is-bottom",
        type: "is-danger"
      });
    }
  }
};
</script>

is-bottom places it at the bottom of the page.

Tooltip

Buefy comes with its own tooltip.

For example, we can write:

<template>
  <div id="app">
    <b-tooltip label="Tooltip right" position="is-right">
      <button class="button is-dark">Right</button>
    </b-tooltip>
  </div>
</template>

<script>
export default {
  name: "App"
};
</script>

The b-tooltip component is wrapped around the trigger of the tooltip.

label has the tooltip text.

position has the position. It can be changed to other positions like is-left , is-bottom , etc.

We can add a delay with the delay prop:

<template>
  <div id="app">
    <b-tooltip label="Tooltip right" position="is-right" :delay="1000">
      <button class="button is-dark">Right</button>
    </b-tooltip>
  </div>
</template>

<script>
export default {
  name: "App"
};
</script>

Multilined Tooltip

The multilined prop makes it multilined:

<template>
  <div id="app">
    <b-tooltip label="Tooltip right" position="is-right" multilined>
      <button class="button is-dark">Right</button>
    </b-tooltip>
  </div>
</template>

<script>
export default {
  name: "App"
};
</script>

Conclusion

We can add tags and tooltips to our Vue app with Buefy.