Categories
Vue 3

Vue 3 — More Complex Render Functions

Vue 3 is in beta and it’s subject to change.

Vue 3 is the up and coming version of Vue front end framework.

It builds on the popularity and ease of use of Vue 2.

In this article, we’ll look at how to create render functions with Vue 3.

Replacing Template Features with Render Functions

We can replace template features with render functions.

Directives like v-if and v-for can be replaced within render functions.

v-if can be replaced an if statement.

v-for can be replaced with an array of items.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <todo-list :todos="todos"></todo-list>
    </div>
    <script>
      const app = Vue.createApp({
        data() {
          return {
            todos: [{ name: "eat" }, { name: "drink" }, { name: "sleep" }]
          };
        }
      });

      app.component("todo-list", {
        props: ["todos"],
        render() {
          if (this.todos.length) {
            return Vue.h(
              "div",
              this.todos.map(todo => {
                return Vue.h("div", todo.name);
              })
            );
          } else {
            return Vue.h("div", "no todos.");
          }
        }
      });

      app.mount("#app");
    </script>
  </body>
</html>

We created the todo-list component with the if statement to check the length fo the this.todos array.

And we called map to return an array of divs with the name .

v-on

The equivalent of the v-on directive is the on methods in the object in the 2nd argument.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <custom-div></custom-div>
    </div>
    <script>
      const app = Vue.createApp({});

      app.component("custom-div", {
        render() {
          return Vue.h(
            "div",
            {
              onClick: $event => console.log("clicked", $event.target)
            },
            "click me"
          );
        }
      });

      app.mount("#app");
    </script>
  </body>
</html>

We created a custom-div component with a div.

The 2nd argument is an object that has the onClick method, which listens to clicks on the div.

The 3rd argument has the content between the div tags.

v-model

v-model ‘s equivalent is the modelValue prop and the onInput method.

For instance, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <custom-input v-model="value"></custom-input>
      <p>{{value}}</p>
    </div>
    <script>
      const app = Vue.createApp({
        data() {
          return {
            value: ""
          };
        }
      });

      app.component("custom-input", {
        props: ["modelValue"],
        render() {
          return Vue.h("input", {
            modelValue: this.modelValue,
            onInput: ev => this.$emit("update:modelValue", ev.target.value)
          });
        }
      });

      app.mount("#app");
    </script>
  </body>
</html>

We have the modelValue prop with the custom-input component.

this.modelValue has the prop’s value.

We set that as the modelValue property’s value.

And then we emit the update:modelValue event to send the value to the parent.

Now when we type in something, it’ll be synchronized with the value state.

So we’ll see what we typed displayed.

Event Modifiers

Event modifiers can also be replaced with render functions.

For instance, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <custom-div></custom-div>
    </div>
    <script>
      const app = Vue.createApp({});

      app.component("custom-div", {
        render() {
          return Vue.h(
            "div",
            {
              onClick: {
                handler: ev => console.log(ev),
                capture: true
              },
              onKeyUp: {
                handler: ev => console.log(ev),
                once: true
              },
              onMouseOver: {
                handler: ev => console.log(ev),
                once: true,
                capture: true
              }
            },
            "click me"
          );
        }
      });

      app.mount("#app");
    </script>
  </body>
</html>

to add the event handler methods.

The options are the modifiers.

Conclusion

We can replace various directives with their equivalents with render functions.

Categories
Top Vue Packages

Top Vue Packages for Checking Network Status, Checkboxes and Radio Buttons

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In this article, we’ll look at the best packages for checking network status, particle background, checkboxes and radio buttons, and infinite scrolling.

Vue Offline

Vue Offline is a good plugin for detecting whether a Vue app is online for offline.

To use it, we run:

npm i vue-offline

Then we can use it by writing:

main.js

import Vue from "vue";
import App from "./App.vue";
import VueOffline from "vue-offline";

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

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

App.vue

<template>
  <div>
    <p v-if="isOnline">online</p>
    <p v-if="isOffline">Toffline</p>
  </div>
</template>

<script>
export default {
  mounted() {
    this.$on("offline", () => {
      console.log('offline')
    });
  }
};
</script>

We register the plugin., Then we can use the isOnline and isOffline properties to check whether the app is online or offline.

Also, we can use the $on method to listen to network status changes.

We can also save data to local storage to make the data available offline.

To save the data, we can write:

<template>
  <div>
    <p v-if="isOnline">online</p>
    <p v-if="isOffline">Toffline</p>
  </div>
</template>

<script>
export default {
  mounted() {
    this.$offlineStorage.set("user", { foo: "bar" });
  }
};
</script>

We use the this.$offlineStorage.set method to save the data.

The first argument is the key and the 2nd is the value.

We can use this.$offlineStorage.get to get the value by the key.

vue-particles

We can use vue-particles to display a particles background in our Vue app.

To use it, we run:

npm i vue-particles

to install the package.

Then we can write:

main.js

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

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

App.vue

<template>
  <div>
    <vue-particles color="#dedede"></vue-particles>
  </div>
</template>

<script>
export default {};
</script>

to use it.

We have the vue-particles component to display the background.

color is the color of the particles.

There are many other things we can customize.

Line colors, width, opacity, distance, speed, opacity, all can be customized.

vue-checkbox-radio

vue-checkbox-radio lets us add radio buttons or checkboxes to our Vue app.

To use it, we run:

npm install vue-checkbox-radio --save

to install it.

Then we can write:

main.js

import Vue from "vue";
import App from "./App.vue";
import CheckboxRadio from "vue-checkbox-radio";

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

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

App.vue

<template>
  <div>
    <checkbox name="agree" v-model="agree" value="1">
      I agree to the
      <a href="#">terms</a>
    </checkbox>
  </div>
</template>

<script>
export default {
  data() {
    return { agree: false };
  }
};
</script>

to use it.

checkbox is the component for adding the checkbox.

The content between the tags will be the content beside the checkbox.

name is the name attribute of the checkbox.

v-model binds the checked value to the agree state.

We can also add radio buttons with it.

To do that, we write:

<template>
  <div>
    <radio name="robot" value="1" v-model="isRobot">I'm a robot</radio>
    <radio name="robot" value="0" v-model="isRobot">I'm not a robot</radio>
    <p>{{isRobot}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return { isRobot: false };
  }
};
</script>

We just bind v-model to the same state and it’ll be set when we check it.

The name attribute of one set of checkboxes will have the same name.

vue-mugen-scroll

vue-mugen-scroll is an infinite scrolling library for Vue apps.

To use it, we can install it by running:

npm i vue-mugen-scroll

Then we write:

<template>
  <div id="app">
    <div class="list">
      <p v-for="n in num" :key="n">{{n}}</p>
    </div>
    <mugen-scroll :handler="fetchData" :should-handle="!loading">loading...</mugen-scroll>
  </div>
</template>

<script>
import MugenScroll from "vue-mugen-scroll";
export default {
  data() {
    return { loading: false, num: 50 };
  },
  methods: {
    fetchData() {
      this.loading = true;
      this.num += 50;
      this.loading = false;
    }
  },
  components: { MugenScroll }
};
</script>

to add infinite scrolling to our component.

We put whatever needs infinite scrolling above the mugen-scroll component so that it watches the scroll position and load more data if needed.

handler is the prop for the method to fetch data.

should-handle is the state that loads the handler.

Conclusion

vue-mugen-scroll lets us add infinite scrolling.

Vue Offline lets us check network status in a Vye app.

vue-particles lets us create a particle background.

vue-checkbox-radio lets us add checkbox or radio buttons.

Categories
Top Vue Packages

Top Vue Packages for Adding a Password Strength Meter, Charts, and File Uploader

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In this article, we’ll look at the best packages for adding a password strength meter, charts, and file uploader.

vue-password-strength-meter

vue-password-strength-meter is an easy to add password strength meter for our Vue app.

To use it, we run:

npm i vue-password-strength-meter zxcvbn

to install it.

zxcvbn is required for measuring the password strength.

Then we can use it by writing:

<template>
  <password v-model="password"/>
</template>

<script>
import Password from "vue-password-strength-meter";
export default {
  components: { Password },
  data() {
    return {
      password: null
    };
  }
};
</script>

We use the password component to add a password input.

We bind to the password state with v-model .

It can be customized with some options.

We can listen to events emitted when the score and feedback events are emitted.

For instance, we can write:

<template>
  <password v-model="password" @score="showScore" @feedback="showFeedback"/>
</template>

<script>
import Password from "vue-password-strength-meter";
export default {
  components: { Password },
  data() {
    return {
      password: null
    };
  },
  methods: {
    showFeedback({ suggestions, warning }) {
      console.log(suggestions);
      console.log(warning);
    },
    showScore(score) {
      console.log(score);
    }
  }
};
</script>

It emits the score event with the password strength score.

The feedback event is emitted with the feedback for our password strength.

We can get these things and display them to the user if we want.

We can customize the styles for the strange meter, success and error classes, labels, and more.

vue-simple-uploader

vue-simple-uploader is a file uploader component for Vue apps.

To use it, we run:

npm i vue-simple-uploader

to install it.

Then we write:

main.js

import Vue from "vue";
import App from "./App.vue";
import uploader from "vue-simple-uploader";

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

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

App.vue

<template>
  <uploader :options="options" class="uploader-example">
    <uploader-unsupport></uploader-unsupport>
    <uploader-drop>
      <p>Drop files here to upload or</p>
      <uploader-btn>select files</uploader-btn>
      <uploader-btn :attrs="attrs">select images</uploader-btn>
      <uploader-btn :directory="true">select folder</uploader-btn>
    </uploader-drop>
    <uploader-list></uploader-list>
  </uploader>
</template>

<script>
export default {
  data() {
    return {
      options: {
        target: "//localhost:3000/upload",
        testChunks: false
      },
      attrs: {
        accept: "image/*"
      }
    };
  }
};
</script>

to add the uploader component to our app.

uploader-unsupport is displayed when the required features are unsupported in the browser.

upload-btn is an upload button.

uploader-drop is the dropzone for the file upload.

uploader-list display the list of files uploaded.

options has the options, including the upload URL.

attres have the items we accept.

There are slots that we can populate to customize our app.

vue-highcharts

We can use the vue-highcharts package to add charts easily with our app.

One special feature is that we can add custom markers for points.

To use it, we run:

npm i vue2-highcharts highcharts

to install it with its dependencies.

Then we can use it by writing:

<template>
  <div>
    <vue-highcharts :options="options" ref="lineCharts"></vue-highcharts>
    <button @click="load">load</button>
  </div>
</template>

<script>
import VueHighcharts from "vue2-highcharts";
const data = {
  name: "New York",
  marker: {
    symbol: "square"
  },
  data: [
    7.0,
    6.9,
    {
      y: 26.5,
      marker: {
        symbol: "url(http://www.highcharts.com/demo/gfx/sun.png)"
      }
    }
  ]
};
export default {
  components: {
    VueHighcharts
  },
  data() {
    return {
      options: {
        chart: {
          type: "spline"
        },
        title: {
          text: "Monthly Average Temperature"
        },
        subtitle: {
          text: "temperature chart"
        },
        xAxis: {
          categories: ["Jan", "Feb", "Mar"]
        },
        yAxis: {
          title: {
            text: "Temperature"
          },
          labels: {
            formatter() {
              return this.value + "°";
            }
          }
        },
        tooltip: {
          crosshairs: true,
          shared: true
        },
        credits: {
          enabled: false
        },
        plotOptions: {
          spline: {
            marker: {
              radius: 4,
              lineColor: "#666666",
              lineWidth: 1
            }
          }
        },
        series: []
      }
    };
  },
  methods: {
    load() {
      const lineCharts = this.$refs.lineCharts;
      lineCharts.delegateMethod("showLoading", "Loading...");
      lineCharts.addSeries(data);
      lineCharts.hideLoading();
    }
  }
};
</script>

We add the vue-highcharts component to add the chart.

options has all the chart options.

chart has the chart type,

title has the title.

subtitle has the subtitle.

xAxis has the x-axis labels.

yAxis has the y-axis labels.

labels has the labels.

formatter has the function to format the labels.

tooltios enable the tooltips. crosshairs enables the labels on the line.

shared enables the other labels.

plotOptions has the markers.

delegateMethod lets us do various things with our chart.

In our example, we use 'showLoading' to show the loading text.

We get the ref of the chart component and then use the addSeries method to add the chart data.

hideLoading hides the loading text.

Conclusion

vue-password-strength-meter provides us with a useful password strength meter.

vue-simple-uploader provides us with a file upload component.

vue-highcharts is a chart library.

Categories
Top Vue Packages

Top Vue Packages for Adding Icons, Rich Text Editor, Image Upload, and Event Calendar

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In this article, we’ll look at the best packages for adding icons, rich text editor, image upload, and event calendar.

vue-fontawesome

vue-fontawesome is a set of components we can use to add Font Awesome icons into our Vue app.

To use it, we run:

npm i --save @fortawesome/fontawesome-svg-core
npm i --save @fortawesome/free-solid-svg-icons
npm i --save @fortawesome/vue-fontawesome

to install all the required packages.

Then we can use it by writing:

main.js

import Vue from "vue";
import App from "./App.vue";
import { library } from "@fortawesome/fontawesome-svg-core";
import { faUserSecret } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
library.add(faUserSecret);

Vue.component("font-awesome-icon", FontAwesomeIcon);
Vue.config.productionTip = false;

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

App.vue

<template>
  <div id="app">
    <font-awesome-icon icon="user-secret"/>
  </div>
</template>

<script>
export default {};
</script>

We call library.add to register the icon we want to use.

We use the font-awesome-icon with the icon prop to specify the icon we want to use.

It works with both the free and pro versions of Font Awesome.

We just have to install different packages for the pro version.

vue-event-calendar

vue-event-calendar is a very simple calendar library for Vue.

To use it, we run:

npm i vue-event-calendar

to install it.

Then we can write:

main.js

import Vue from "vue";
import App from "./App.vue";
import "vue-event-calendar/dist/style.css";
import vueEventCalendar from "vue-event-calendar";
Vue.use(vueEventCalendar, { locale: "en" });
Vue.config.productionTip = false;

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

App.vue

<template>
  <vue-event-calendar :events="demoEvents"></vue-event-calendar>
</template>

<script>
export default {
  data() {
    return {
      demoEvents: [
        {
          date: "2020/11/12",
          title: "eat"
        },
        {
          date: "2020/12/15",
          title: "drink",
          desc: "description",
          customClass: "disabled highlight"
        }
      ]
    };
  }
};
</script>

to use it.

We use the vue-event-calendar to add a calendar to our app.

Then we set the events prop to an array with objects that have the date and title properties to display events.

date is the date of the event. title is the title of the event.

desc is the description.

customClass are classes that we can add to let us style it with our own CSS.

It emits events when the day or month changed, so we can add listeners to listen to those.

We can change the locale with the locale option.

And we can navigate months and dates with the this.$EventCalendar object.

We can write:

this.$EventCalendar.nextMonth()

to move to the next month and:

this.$EventCalendar.preMonth()

to move to the previous month.

And we can write:

this.$EventCalendar.toDate('2020/11/12')

to move to a given date.

vue-img-inputer

vue-img-inputer is a file uploader library for Vue apps.

To use it, we run:

npm i vue-img-inputer

to install it.

Then we write:

main.js

import Vue from "vue";
import App from "./App.vue";
import ImgInputer from "vue-img-inputer";
import "vue-img-inputer/dist/index.css";

Vue.component("ImgInputer", ImgInputer);
Vue.config.productionTip = false;

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

App.vue

<template>
  <img-inputer v-model="file" theme="light" size="large"/>
</template>

<script>
export default {
  data(){
    return {
      file: undefined
    }
  }
};
</script>

to use it.

We register the component and add the CSS.

Then we use the img-inputer component and bind the selected file with v-model .

There are also many other options we can change, like text for errors, URL for images, icons, and more.

It also emits events for when the file changed or file size exceeded.

vue-pell-editor

vue-pell-editor is a rich text editor for Vue apps.

To use it, we install it by running:

npm i vue-pell-editor

Then we write:

main.js

import Vue from "vue";
import App from "./App.vue";
import VuePellEditor from "vue-pell-editor";

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

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

App.vue

<template>
  <div>
    <vue-pell-editor
      v-model="editorContent"
      :actions="editorOptions"
      :placeholder="editorPlaceholder"
      :style-with-css="false"
      default-paragraph-separator="p"
    />
    <p v-html="editorContent"></p>
  </div>
</template>

<script>
export default {
  data: () => ({
    editorContent: "",
    editorOptions: [
      "bold",
      "underline",
      {
        name: "italic",
        result: () => window.pell.exec("italic")
      },
      {
        name: "custom",
        icon: "<b><u><i>C</i></u></b>",
        title: "Custom Action",
        result: () => console.log("YOLO")
      },
      {
        name: "image",
        result: () => {
          const url = window.prompt("image URL");
          if (url) window.pell.exec("insertImage", ensureHTTP(url));
        }
      },
      {
        name: "link",
        result: () => {
          const url = window.prompt("link URL");
          if (url) window.pell.exec("createLink", ensureHTTP(url));
        }
      }
    ],
    editorPlaceholder: "Write something amazing..."
  }),
  methods: {}
};
</script>

to use it.

We add buttons individually with the editorOptions , which we set as the value of the actions prop.

placeholder has the placeholder.

v-model binds to the entered content.

style-with-css indicates whether we want to style with CSS.

Conclusion

vue-fontawesome lets us use Font Awesome icons.

vue-event-calendar displays an event calendar.

vue-img-inputer lets us add image upload capability to our app,

vue-pell-editor is a rich text editor for Vue apps.

Categories
Top Vue Packages

Top Vue Packages for Watching Visibility, Embed Vimeo Videos, and More

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In this article, we’ll look at the best packages for watching visibility, displaying confetti, toasts, focus trap and embed Vimeo videos.

v-visibility-change

We can use v-visibility-change to watch for visibility changes in our elements.

To use it, we run:

npm i vue-visibility-change

Then we can use it by writing:

main.js

import Vue from "vue";
import App from "./App.vue";
import visibility from "vue-visibility-change";

Vue.use(visibility);

visibility.change((evt, hidden) => {
  console.log(evt, hidden);
});

Vue.config.productionTip = false;

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

App.vue

<template>
  <div>
    <div v-visibility-change="visibilityChange" v-for="n in 30" :key="n">item {{n}}</div>
  </div>
</template>
<script>
export default {
  methods: {
    visibilityChange(evt, hidden) {
      console.log(hidden);
    }
  }
};
</script>

We have the v-visibility directive that we pass a handler method into that runs when visibility of an element changes.

Also, we have:

visibility.change((evt, hidden) => {
  console.log(evt, hidden);
});

to watch for visibility changes.

Vue wrapper for Vimeo Embed Player

vue-vimeo-player lets us embed videos from Vimeo in our Vue app.

We install it by running:

npm i vue-vimeo-player

Then we can use it by writing:

<template>
  <div>
    <vimeo-player ref="player" :video-id="videoID"/>
  </div>
</template>

<script>
import { vueVimeoPlayer } from "vue-vimeo-player";

export default {
  data() {
    return {
      videoID: 420233198
    };
  },
  components: { vueVimeoPlayer }
};
</script>

We add the vimeo-player component with the video-id prop to set the Vimeo video ID.

Now we see the Vimeo player with the video.

We can set autoplay, player width and height, looping, and control options.

vue-confetti

We can use vue-confetti to display animated confetti in our Vue app.

To use it, we run:

npm i vue-confetti

to install it.

Then we can use it by writing:

<template>
  <div>
    <main>
      <button @click="start">Start</button>
      <button @click="stop">Stop</button>
      <button @click="love">hearts</button>
    </main>
  </div>
</template>

<script>
import Vue from "vue";
import VueConfetti from "vue-confetti";

Vue.use(VueConfetti);

export default {
  methods: {
    start() {
      this.$confetti.start();
    },

    stop() {
      this.$confetti.stop();
    },

    love() {
      this.$confetti.update({
        particles: [
          {
            type: "heart"
          },
          {
            type: "circle"
          }
        ],
        defaultColors: ["red", "pink", "#ba0000"]
      });
    }
  }
};
</script>

We use the this.$cofetti.start method to show confetti.

this.$confetti.stop stops the confetti.

And this.$confetti.update updates the confetti while we’re showing it.

vue2-toast

vue2-toast lets us add toasts to our Vue app.

To use it, we run:

npm i vue2-toast

to install it.

Then we write:

main.js

import Vue from "vue";
import App from "./App.vue";
import "vue2-toast/lib/toast.css";
import Toast from "vue2-toast";
Vue.use(Toast);

Vue.config.productionTip = false;

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

App.vue

<template>
  <div id="app">
    <button @click="openTop()">top</button>
    <button @click="openCenter()">center</button>
    <button @click="openBottom()">bottom</button>
    <button @click="openLoading()">loading</button>
  </div>
</template>

<script>
export default {
  methods: {
    openTop() {
      this.$toast.top("top");
    },
    openCenter() {
      this.$toast.center("center");
    },
    openBottom() {
      this.$toast("bottom");
    },
    openLoading() {
      this.$loading("loading...");
      setTimeout(() =>{
        this.closeLoading();
      }, 2000);
    },
    closeLoading() {
      this.$loading.close();
    }
  }
};
</script>

to use it.

We register the component and import the CSS.

We can use this.$toast to show toasts in various styles.

top to show toast at the top.

center shows toast ar the center.

openLoading shows a toast with a loading indicator.

close close the loading indicator.

We can change the duration, type of toast, and styling options like word wrap and width.

focus-trap-vue

focus-trap-vue lets us keep focus on the element inside the provided component.

We can install it by running:

npm i focus-trap-vue

Then we can use it by writing:

<template>
  <div id="app">
    <focus-trap v-model="isActive">
      <input ref="nameInput">
    </focus-trap>
  </div>
</template>

<script>
import { FocusTrap } from "focus-trap-vue";

export default {
  components: {
    FocusTrap
  },
  data() {
    return {
      isActive: true
    };
  }
};
</script>

We use the focus-trap component to set focus on the input inside.

isActive indicates that the focus is a trap is active if it’s true .

Conclusion

v-visibility-change is a plugin to watch the visibility status of an element.

Vue wrapper for Vimeo Embed Player lets us embed Vimeo videos to our app.

vue-confetti is a fun plugin to lets us display confetti in our Vue app.

vue2-toast lets us display toasts with ease.

focus-trap-vue lets us focus on an element.