Categories
Top Vue Packages

Top Vue Packages for Adding Avatar, Slides, and Tooltips

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 how the best packages for adding avatars, swiping, and tooltips.

vue-avatar

vue-avatar lets us add an avatar to our Vue app easily.

To use it, we run:

npm i vue-avatar

Then we can use it by importing the Avatar component:

<template>
  <div class="demo">
    <avatar username="Jane Smith"></avatar>
  </div>
</template>

<script>
import Avatar from "vue-avatar";

export default {
  name: "app",
  components: {
    Avatar
  }
};
</script>

We just set the name as the value of the username property to display a circle with the initials.

To add an image, we can use the src prop:

<template>
  <div class="demo">
    <avatar src="http://placekitten.com/200/200"></avatar>
  </div>
</template>

<script>
import Avatar from "vue-avatar";

export default {
  name: "app",
  components: {
    Avatar
  }
};
</script>

It also supports changing many other options like color, background, size, roundedness, custom styling, and more.

vue-awesome-swiper

The vue-awesome-swiper component lets us add a slider to add that we can swipe to our Vue app.

It’s great for creating carousels and slide shows.

To install it, we run:

npm i vue-awesome-swiper

Then we can use it by registering the plugin and importing the styles:

main.js

import Vue from "vue";
import App from "./App.vue";
import "swiper/css/swiper.css";
import VueAwesomeSwiper from "vue-awesome-swiper";
Vue.use(VueAwesomeSwiper);

Vue.config.productionTip = false;

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

Then we can use it in our component by writing:

<template>
  <swiper ref="mySwiper" :options="swiperOptions">
    <swiper-slide v-for="n in 10" :key="n">Slide {{n}}</swiper-slide>
    <div class="swiper-pagination" slot="pagination"></div>
  </swiper>
</template>

<script>
export default {
  name: "carrousel",
  data() {
    return {
      swiperOptions: {
        pagination: {
          el: ".swiper-pagination"
        }
      }
    };
  },
  computed: {
    swiper() {
      return this.$refs.mySwiper.$swiper;
    }
  },
  mounted() {
    this.swiper.slideTo(3, 1000, false);
  }
};
</script>

swiper-slide has the slides.

swiperOptions has the options. We set the button for changing slide to have the class swiper-pagination .

The swiper object is available in the this.$refs.mySwiper.$swiper property.

Then we can call methods on it like the slideTo method to slide to the slide with the given index.

1000 is the delay.

The 3rd argument indicates that we don’t want to run callbacks.

Alternatively, we can use it as a directive.

For instance, we can write:

<template>
  <div v-swiper:mySwiper="swiperOptions">
    <div class="swiper-wrapper">
      <div class="swiper-slide" :key="n" v-for="n in 10">
        <img src="http://placekitten.com/200/200">
        <p>slide {{n}}</p>
      </div>
    </div>
    <div class="swiper-pagination"></div>
  </div>
</template>

<script>
export default {
  name: "carrousel",
  data() {
    return {
      swiperOptions: {
        pagination: {
          el: ".swiper-pagination"
        }
      }
    };
  }
};
</script>

We used the v-swiper:mySwiper directive to create our swiper with the swiperOptions object.

Now we get the same slider, but without sliding automatically to the given slide.

The classes must be set so that we get the right items on the slide.

It can handle many events like clicking sides, transitions, and more.

v-tooltip

To add a tooltip to our Vue app, we can use the v-tooltip component.

To install it, we run:

npm i v-tooltip

Then we can use it by writing:

import Vue from "vue";
import App from "./App.vue";
import VTooltip from "v-tooltip";

Vue.use(VTooltip);

Vue.config.productionTip = false;

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

to register the components and directives.

Then in our component, we can write:

<template>
  <div>
    <button v-tooltip="`You have ${count} messages`">click me</button>
  </div>
</template>

<script>
export default {
  data() {
    return { count: 100 };
  }
};
</script>

to see a tooltip when we hover over the button.

The v-tooltip component lets us add the tooltip.

We can also change the position with some modifiers:

<template>
  <div>
    <button v-tooltip.right="`You have ${count} messages`">click me</button>
  </div>
</template>

<script>
export default {
  data() {
    return { count: 100 };
  }
};
</script>

We can also add classes so that we can style the tooltip:

<template>
  <div>
    <button
      v-tooltip.right="{ content: `You have ${count} messages`, classes: ['a', 'b'] }"
    >click me</button>
  </div>
</template>

<script>
export default {
  data() {
    return { count: 100 };
  }
};
</script>

We have the classes property in the object. content has the content.

Conclusion

The vue-avatar package lets us add an avatar easily.

The v-tooltip package is a great package for adding tooltips into our app.

vue-awesome-swiper lets us add slides to our app.

Categories
Top Vue Packages

Top Vue Packages for Adding Draggable Lists and Text Editing Capabilities

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 how the best packages for adding draggable lists into a Vue app.

vuedraggable

The vuedraggable package is a package that we can use to add draggable lists to our app.

To install it, we run:

npm i vuedraggable

Then we can use it by writing:

<template>
  <div class="demo">
    <draggable v-model="arr" group="people" @start="drag=true" @end="drag=false">
      <div v-for="element in arr" :key="element.id">{{element.name}}</div>
    </draggable>
  </div>
</template>

<script>
import draggable from "vuedraggable";

export default {
  components: {
    draggable
  },
  data() {
    return {
      arr: [
        {
          id: 1,
          name: "foo"
        },
        {
          id: 2,
          name: "bar"
        },
        {
          id: 3,
          name: "baz"
        }
      ]
    };
  }
};
</script>

We registered the draggable component.

Then we nest out list inside it.

We also set our start and end handlers, which are run when we start and stop dragging respectively.

v-model binds to the latest value of arr .

Now we can drag and drop the names.

We can also use it with transition-group :

<template>
  <div class="demo">
    <draggable v-model="arr" group="people" @start="drag = true" @end="drag = false">
      <transition-group name="list">
        <div v-for="element in arr" :key="element.id">{{element.name}}</div>
      </transition-group>
    </draggable>
  </div>
</template>

<script>
import draggable from "vuedraggable";

export default {
  components: {
    draggable
  },
  data() {
    return {
      arr: [
        {
          id: 1,
          name: "foo"
        },
        {
          id: 2,
          name: "bar"
        },
        {
          id: 3,
          name: "baz"
        }
      ]
    };
  }
};
</script>

<style>
.list-enter-active,
.list-leave-active {
  transition: all 1s;
}
.list-enter, .list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}
</style>

We just put it inside the draggable component to add transition effects when dragging and dropping.

We can add a slot for the footer or header.

For instance, we can write:

<template>
  <div class="demo">
    <draggable v-model="arr" group="people" @start="drag = true" @end="drag = false">
      <p slot="header">header</p>
      <div v-for="element in arr" :key="element.id">{{element.name}}</div>
      <p slot="footer">footer</p>
    </draggable>
  </div>
</template>

<script>
import draggable from "vuedraggable";

export default {
  components: {
    draggable
  },
  data() {
    return {
      arr: [
        {
          id: 1,
          name: "foo"
        },
        {
          id: 2,
          name: "bar"
        },
        {
          id: 3,
          name: "baz"
        }
      ]
    };
  }
};
</script>

There are many other options that we can use to configure it, including changing the tag of the rendered elements, setting the list, watching move events, and more.

TinyMCE Vue

TinyMCE has a Vue version, so we can use the TinyMCE rich text editor without hassle.

To install it, we run:

npm install --save @tinymce/tinymce-vue

Then we can use it by writing:

<template>
  <div class="demo">
     <editor
       api-key="no-api-key"
       :init="{
         height: 500,
         menubar: false,
         plugins: [
           'advlist autolink lists link image charmap print preview anchor',
           'searchreplace visualblocks code fullscreen',
           'insertdatetime media table paste code help wordcount'
         ],
         toolbar:
           'undo redo | formatselect | bold italic backcolor |
           alignleft aligncenter alignright alignjustify |
           bullist numlist outdent indent | removeformat | help'
       }"
     />
  </div>
</template>

<script>
import Editor from '@tinymce/tinymce-vue'

export default {
   name: 'app',
   components: {
     'editor': Editor
   }
 }
</script>

We just import the component and register it.

Then we specify our plugins and other options.

We can add v-model to bind the inputted value to a state variable:

<template>
  <div class="demo">
    <editor
      api-key="no-api-key"
      :init="{
         height: 200,
         menubar: false,
         plugins: [
           'advlist autolink lists link image charmap print preview anchor',
           'searchreplace visualblocks code fullscreen',
           'insertdatetime media table paste code help wordcount'
         ],
         toolbar:
           'undo redo | formatselect | bold italic backcolor |
           alignleft aligncenter alignright alignjustify |
           bullist numlist outdent indent | removeformat | help'
       }"
      v-model="content"
    />
    <p v-html="content"></p>
  </div>
</template>

<script>
import Editor from "@tinymce/tinymce-vue";

export default {
  name: "app",
  components: {
    editor: Editor
  },
  data() {
    return {
      content: ""
    };
  }
};
</script>

We have the v-model prop bound to content. And we added the p element with the v-html directive set to content to see what we typed.

Now we get a text editor in our app without much hassle.

Conclusion

We can use the vuedraggable library to lets us make list items draggable and droppable.

The Vue version of the TinyMCE is full of features and it’s easy to add.

Categories
Top Vue Packages

Top Vue Packages for Adding Drag and Drop and Watching Resizing

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 how the best packages for adding drag and drop and watching elements resizing to our Vue app.

VueDraggableResizable

VueDraggableResizable is an easy to use the package to let us make comments draggable and resizable.

To use it, we install it by running:

npm i vue-draggable-resizable

Then we can use it by writing:

import Vue from "vue";
import App from "./App.vue";
import VueDraggableResizable from "vue-draggable-resizable";

import "vue-draggable-resizable/dist/VueDraggableResizable.css";

Vue.component("vue-draggable-resizable", VueDraggableResizable);
Vue.config.productionTip = false;

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

to register the component and add the styles.

Then in our component, we write:

<template>
  <div id="app">
    <div id="draggable">
      <vue-draggable-resizable
        :w="100"
        :h="100"
        [@dragging](http://twitter.com/dragging "Twitter profile for @dragging")="onDrag"
        [@resizing](http://twitter.com/resizing "Twitter profile for @resizing")="onResize"
        :parent="true"
      >
        <p>drag me ({{x}},{{y}})</p>
      </vue-draggable-resizable>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      width: 0,
      height: 0,
      x: 0,
      y: 0
    };
  },
  methods: {
    onResize(x, y, width, height) {
      this.x = x;
      this.y = y;
      this.width = width;
      this.height = height;
    },
    onDrag(x, y) {
      this.x = x;
      this.y = y;
    }
  }
};
</script>

<style>
#draggable {
  height: 500px;
  width: 500px;
  position: relative;
}
</style>

We have a 500px by 500px div that we can drag and resize thanks to the vue-draggable-resizable component.

The x and y coordinates change and can be listened to with the onDrag handler, which has the latest coordinates in the parameters.

Likewise, we can do the same for resize:

<template>
  <div id="app">
    <div id="draggable">
      <vue-draggable-resizable
        :w="100"
        :h="100"
        [@dragging](http://twitter.com/dragging "Twitter profile for @dragging")="onDrag"
        [@resizing](http://twitter.com/resizing "Twitter profile for @resizing")="onResize"
        :parent="true"
      >
        <p>drag me ({{x}},{{y}})</p>
        <p>size ({{width}}x{{height}})</p>
      </vue-draggable-resizable>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      width: 0,
      height: 0,
      x: 0,
      y: 0
    };
  },
  methods: {
    onResize(x, y, width, height) {
      this.x = x;
      this.y = y;
      this.width = width;
      this.height = height;
    },
    onDrag(x, y) {
      this.x = x;
      this.y = y;
    }
  }
};
</script>

<style>
#draggable {
  height: 500px;
  width: 500px;
  position: relative;
}
</style>

The onResize method for the coordinates and the size.

Props

It comes with other props like class-name to set the class name.

class-name-draggable to add styles with draggable is enabled.

class-name-resizable lets us style the element when it’s resized.

class-name-resizing lets us add styles when it’s resizing.

class-name-handle styles the handles.

disable-user-select lets us disable user to select.

There are many other props that we can use to style and handle events.

The initial x and y coordinates can also be set with the props of the same name.

vue-resize

We can watch elements being resized with the vue-resize package.

To use it, we install it by running:

npm i vue-resize

Then we register the component by adding:

import Vue from "vue";
import App from "./App.vue";
import "vue-resize/dist/vue-resize.css";
import VueResize from "vue-resize";

Vue.use(VueResize);

Vue.config.productionTip = false;

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

It comes with styles and the resize-observer component.

Then in our component, we add:

<template>
  <div class="demo">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eu facilisis lorem. In arcu nisl, vulputate id diam eget, ultricies aliquet neque. Phasellus sapien lacus, consectetur ut nisi quis, mattis tincidunt ante. Aliquam ultrices nisl ornare augue laoreet, a vehicula libero consequat. Sed aliquam aliquet turpis, ut sodales elit sodales sit amet. Donec ullamcorper velit neque, in maximus odio tempus eu. Praesent ullamcorper, nibh sodales maximus feugiat, erat tellus condimentum sem, ac convallis tellus diam suscipit tellus. Proin egestas tellus neque. Vestibulum porttitor tempus tellus sit amet volutpat. Sed urna nibh, molestie non pulvinar in, accumsan nec nisl.</p>
    <resize-observer @notify="handleResize"/>
  </div>
</template>

<script>
export default {
  methods: {
    handleResize({ width, height }) {
      console.log("resized", width, height);
    }
  }
};
</script>

<style scoped>
.demo {
  position: relative;
}
</style>

We set the notify handler to handleResize to watch for size changes.

The width and height are in the handler for us to use.

Conclusion

We can use the vue-draggable-resizable package to let us create elements that are draggable and resizable.

The vue-resize package lets us watch for elements being resized.

Categories
JavaScript Best Practices

JavaScript Best Practices — Variable Naming Conventions

JavaScript is a very forgiving language. It’s easy to write code that runs but has issues in it.

In this article, we’ll look at best practices for naming JavaScript variables.

When You Should Have a Naming Convention

We need some naming conventions so that everyone working on the project are on the same page.

Also, we run a program over to another person for changes, they’ll also be on the same page.

It also makes reviewing things easier as we don’t have to find out what something means.

When a program is so big that we can’t hold them in brains, then having conventions reduce the cognitive load of our brains.

Informal Naming Conventions

Naming conventions vary between languages, but there’re some that apply to language.

Variable names and functions names are both camelCase except for classes constructor functions, which are named in PascalCases.

Objects are in camelCase.

To make identifying global variables easier, we can put a g prefix before the global variable.

Member variables are named the same as other variables in JavaScript.

But we may put a _ before the member variable of a class to distinguish them from other variables.

Other Conventions for Names in JavaScript

Index variables are named with short names like i and j .

Constants are named with all caps with underscores in between words.

get and set are used for accessor methods.

Property names of objects are also named with camel case.

Parameters of functions are also camel case as with variables.

Standardized Prefixes

We may want to prefix our variables names to make identifying them easier.

To do that, we may add semantic prefixes to some variables to make them easier to understand.

For instance, we may have c for count, first for the first element of an array, g for a global variable, i for array index, and last for the last element of an array.

The m prefix may be used for class instance variables. max for the maximum of a set of numbers, min is the minimum number from an array.

Advantages of Standardized Prefixes

Standardized prefixes give us all the advantages of standard naming conventions,

We don’t have to dig deep to find what something means.

The distinctions between prefixes like min , first , last and max are helpful.

Creating Short Names That Are Readable

If we abbreviate variable names, then we should make sure that they’re abbreviations that everyone understands.

There are many ways to abbreviate variable names.

We can use standard abbreviations.

Nonleading vowels should be removed from abbreviations. For instance, apple becomes appl .

Articles like and , or , the , etc. should be removed.

The first letter or first few letters should be used.

Truncating words consistently may also be used for naming variables.

Using the first and last letters of each word is another possibility.

Every significant word in the name can also be used.

Useless suffixes can also be removed.

These are all possible ways that we can abbreviate variable names.

Phonetic Abbreviations

We can also use phonetic abbreviations. However, it’s not very clear so it’s probably a bad idea to use them.

Good Practices When Abbreviating Variable Names

We shouldn’t abbreviate by removing one character from a word.

Since it’s only one character shorter, it doesn’t help us too much.

Abbreviating consistent is also a good idea. We should keep some conventions to remove our cognitive load.

Creating names that we can pronounce is also good.

Combinations that may result in misreading or mispronunciation also isn’t good. So sEnd is better than send , for example.

A thesaurus can help us resolve naming collisions if we do run into them.

If we have short names, we may want to document them so that people can understand what those names stand for.

A project-level document for names that people might not understand is also a good idea to have.

Conclusion

To make sure that everyone understands the names that we name, we got to name them clearly.

If we abbreviate, then we got to stick to a convention for abbreviation and keep a list of abbreviations if needed.

Categories
JavaScript Best Practices

JavaScript Best Practices- Variable Declarations, IIFEs, and Yoda

JavaScript is a very forgiving language. It’s easy to write code that runs but has mistakes in it.

In this article, we look at why we should put var declarations on top, wrapping IIFES, and Yoda expressions.

Put Variable Declarations to be at the Top of Their Scope

We should put variable declarations on the top of their scope so that we’re sure that we can access them from the beginning.

One confusing feature of JavaScript is that variables declared with var can be hoisted.

The declaration is hoisted but the value assigned to it is not.

For instance, if we have:

console.log(x)
var x = 1;

Then we should see that x is undefined from the console log output because the var x part is hoisted to the top, but setting the value is still done after the console log call.

var is function scoped, so it’s fine for it to be declared on top of a function block.

But they should all be declared before any code inside is run. So, we shouldn’t have code like:

function foo() {
  var first;
  first = 1;
  var second;
}

In the code above, the second variable is written after the first = 1; expression, so second will be hoisted to the top of the function.

If we log it as follows:

function foo() {
  var first;
  console.log(second);
  first = 1;
  var second = 2;
}

foo()

Then we get that second is undefined since var second is hoisted to the top, but the rest of the expression stays at the bottom.

As we can see, having var variables below the top section of a function or at the top level of a script is a pain. We’ve to know that some part of it is hoisted.

Therefore, we should just put all of the var declarations at the top. If it’s a script, we should put var declarations at the top of the top-level of a script as follows:

var foo = 1;
var bar = 2;
//...

Then we don’t have to worry about hoisting.

Likewise, in functions, we should put all the var declarations on top as follows:

function baz() {
  var foo = 1;
  var bar = 2;
  //...
}

It’s just painful to have them anywhere else. Better yet, we should use let and const instead of var . They’re block-scoped and they aren’t hoisted so that they can only be referenced after they’re defined.

Wrap Our IIFEs

IIFEs are immediately invoked function expressions. They’re functions that are called immediately after they’re declared.

We should wrap them to make sure that we’re calling the function and avoid syntax errors.

For instance, if we have the following code:

const bar = () => ({
  a: 1
})();

The () in the end, we didn’t call the arrow function we declared. And if we log bar , we just get the function itself.

Instead, we should write:

const bar = (() => ({
  a: 1
}))()

The code above wraps the whole function in parentheses. Then when we add the () after it, the function we defined is actually called.

If we want to call a function method like bind , call , and apply right after the function is defined, we can do the following:

const x = (function() {
  return this
}).call({
  a: 1
})

This way, call actually is called on the function we defined.

Therefore, we should always wrap our IIFEs with parentheses so that it’ll be called if we add () after it.

No Yoda Conditions

A condition expression like the following:

if ("apple" === fruit) {
  _// ..._
}

is called a Yoda condition because it reads like ‘if apple equals the fruit’, which like how Yoda in Star Wars speaks.

If we flip the operands in the condition as follows:

if (fruit === "apple") {
  _// ..._
}

Then the condition reads like ‘if the fruit equals apple’, which is more natural for many people.

This is more of a style preference since we may be able to use the = operator instead of === to assign 'apple' to fruit instead of comparing them with the === operator.

But it reads more naturally, so it’s a matter of preference rather than something we should change.

Conclusion

Yoda expressions are things like "apple" === fruit . It’s more of a matter of preference in how we order the operands.

IIFEs should always be wrapped with parentheses so that we make sure it’s always called.

var declarations should always be on top of their scope so that there’s no ambiguity with hoisting.