Categories
PrimeVue

Vue 3 Development with the PrimeVue Framework — Knob and Listbox

PrimeVue is a UI framework that’s compatible with Vue 3.

In this article, we’ll look at how to get started with developing Vue 3 apps with PrimeVue.

Knob

PrimeVue’s Knob component lets us add a dial that displays a numeric value on the screen with a bar.

We can also use it to set numeric values.

To add it, we can write:

main.js

import { createApp } from "vue";
import App from "./App.vue";
import PrimeVue from "primevue/config";
import Knob from 'primevue/knob';
import 'primevue/resources/primevue.min.css'
import 'primevue/resources/themes/saga-blue/theme.css'
import 'primeicons/primeicons.css'
import 'primeflex/primeflex.css';

const app = createApp(App);
app.use(PrimeVue);
app.component("Knob", Knob);
app.mount("#app");

App.vue

<template>
  <div>
    <Knob v-model="value" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: 50,
    };
  },
  methods: {},
};
</script>

We register the component in main.js .

Then we add it into the App component and bind the selected value to value with v-model .

We can change its size with the size prop by setting the size in pixels:

<template>
  <div>
    <Knob v-model="value" :size="200" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: 50,
    };
  },
  methods: {},
};
</script>

Listbox

PrimeVue comes with a listbox component.

For example, we can write:

main.js

import { createApp } from "vue";
import App from "./App.vue";
import PrimeVue from "primevue/config";
import Listbox from 'primevue/listbox';
import 'primevue/resources/primevue.min.css'
import 'primevue/resources/themes/saga-blue/theme.css'
import 'primeicons/primeicons.css'
import 'primeflex/primeflex.css';

const app = createApp(App);
app.use(PrimeVue);
app.component("Listbox", Listbox);
app.mount("#app");

App.vue

<template>
  <div>
    <Listbox v-model="selectedCity" :options="cities" optionLabel="name" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      selectedCity: null,
      cities: [
        { name: "Miami", code: "MI" },
        { name: "Rome", code: "RM" },
        { name: "London", code: "LDN" },
        { name: "Istanbul", code: "IST" },
        { name: "Paris", code: "PRS" },
      ],
    };
  },
  methods: {},
};
</script>

The options prop lets us specify the options.

optionLabel has the property name of each entry with the value to display.

We can let users select multiple items with the multiple prop:

<template>
  <div>
    <Listbox
      v-model="selectedCity"
      :options="cities"
      optionLabel="name"
      multiple
    />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      selectedCity: null,
      cities: [
        { name: "Miami", code: "MI" },
        { name: "Rome", code: "RM" },
        { name: "London", code: "LDN" },
        { name: "Istanbul", code: "IST" },
        { name: "Paris", code: "PRS" },
      ],
    };
  },
  methods: {},
};
</script>

We can customize how the items are displayed by writing:

<template>
  <div>
    <Listbox
      v-model="selectedCity"
      :options="cities"
      optionLabel="name"
      multiple
    >
      <template #option="slotProps">
        <div>
          <b>{{ slotProps.option.name }}</b>
        </div>
      </template>
    </Listbox>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      selectedCity: null,
      cities: [
        { name: "Miami", code: "MI" },
        { name: "Rome", code: "RM" },
        { name: "London", code: "LDN" },
        { name: "Istanbul", code: "IST" },
        { name: "Paris", code: "PRS" },
      ],
    };
  },
  methods: {},
};
</script>

We populate the option slot to customize how the items are displayed.

slotProps.option has the item.

The filter prop adds an input box to let us filter the conten

Conclusion

We can add knobs and listboxes into our Vue 3 app with the PrimeVue framework.

Categories
PrimeVue

Vue 3 Development with the PrimeVue Framework — Switch, Text Input, and Float Label

PrimeVue is a UI framework that’s compatible with Vue 3.

In this article, we’ll look at how to get started with developing Vue 3 apps with PrimeVue.

Switch

PrimeVue comes with the InputSwitch component that renders a switch.

To add it, we can write:

main.js

import { createApp } from "vue";
import App from "./App.vue";
import PrimeVue from "primevue/config";
import InputSwitch from 'primevue/inputswitch';
import 'primevue/resources/primevue.min.css'
import 'primevue/resources/themes/saga-blue/theme.css'
import 'primeicons/primeicons.css'
import 'primeflex/primeflex.css';

const app = createApp(App);
app.use(PrimeVue);
app.component("InputSwitch", InputSwitch);
app.mount("#app");

App.vue

<template>
  <div>
    <InputSwitch v-model="checked" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      checked: false,
    };
  },
  methods: {},
};
</script>

We bind the switch’s value to a reactive property with v-model .

Text Input

We can add the text input by using the InputText component.

To add it, we write:

main.js

import { createApp } from "vue";
import App from "./App.vue";
import PrimeVue from "primevue/config";
import InputText from 'primevue/inputtext';
import 'primevue/resources/primevue.min.css'
import 'primevue/resources/themes/saga-blue/theme.css'
import 'primeicons/primeicons.css'
import 'primeflex/primeflex.css';

const app = createApp(App);
app.use(PrimeVue);
app.component("InputText", InputText);
app.mount("#app");

App.vue

<template>
  <div>
    <InputText type="text" v-model="value" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: '',
    };
  },
  methods: {},
};
</script>

We bind the entered value to a reactive property v-model .

Also, we can add icons beside the input with the i element with a few classes:

<template>
  <div>
    <span class="p-input-icon-left">
      <i class="pi pi-search" />
      <InputText type="text" v-model="value" placeholder="Search" />
    </span>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

The p-input-icon-left class lets us add an icon to the left side of the input box.

p-input-icon-right lets us add an icon to the right side of the input box.

The p-input-filled class lets us add a gray background to the input box:

<template>
  <div class="p-input-filled">
    <InputText type="text" v-model="value" placeholder="Search" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

Float Label

We can add float labels into our app.

For example, we can write:

<template>
  <div class="p-fluid p-grid">
    <div class="p-m-6">
      <span class="p-float-label">
        <InputText id="inputtext" type="text" v-model="value" />
        <label for="inputtext">InputText</label>
      </span>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

to add it.

We add the p-float-label class to the container to let us add the float label.

Then we add the label element inside the container to make it a float label.

This also works with the Chips , InputMask , InputNumber , MultiSelect , and Textarea components.

Conclusion

We can add switches, text inputs, and float labels into our Vue 3 app with PrimeVue.

Categories
PrimeVue

Vue 3 Development with the PrimeVue Framework — Input Mask and Numeric Inputs

PrimeVue is a UI framework that’s compatible with Vue 3.

In this article, we’ll look at how to get started with developing Vue 3 apps with PrimeVue.

Input Mask

A PrimeVue input mask can be specified with the following parts:

  • a — Alpha character (A-Z,a-z)
  • 9 — Numeric character (0–9)
  • * — Alphanumeric character (A-Z,a-z,0–9)

We can specify the placeholders for the input mask with tyhe slotChar prop:

<template>
  <div>
    <InputMask v-model="value" mask="99/99/9999" slotChar="mm/dd/yyyy" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

slotChar ‘s value is displayed as the placeholder.

We can specify optional values with the question mark:

<template>
  <div>
    <InputMask v-model="value" mask="(999) 999-9999? x99999" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

Numeric Input

PrimeVue’s InputNumber component renders as a numeric input.

To add it, we write:

main.js

import { createApp } from "vue";
import App from "./App.vue";
import PrimeVue from "primevue/config";
import InputNumber from 'primevue/inputnumber';
import 'primevue/resources/primevue.min.css'
import 'primevue/resources/themes/saga-blue/theme.css'
import 'primeicons/primeicons.css'
import 'primeflex/primeflex.css';

const app = createApp(App);
app.use(PrimeVue);
app.component("InputNumber", InputNumber);
app.mount("#app");

App.vue

<template>
  <div>
    <InputNumber v-model="value" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

We can only enter numbers into InputNumber components.

Also, we can set the mode prop to let us enter decimal numbers:

<template>
  <div>
    <InputNumber
      v-model="value"
      mode="decimal"
      :minFractionDigits="2"
      :maxFractionDigits="2"
    />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

We add the minFractionDigits and maxFractionDigits props to let us specify the number of decimal digits we can enter.

The locale prop lets us change the format of the number according to the locale:

<template>
  <div>
    <InputNumber v-model="value" locale="en-IN" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

We can also specify the currency with the currency prop:

<template>
  <div>
    <InputNumber v-model="value" currency="EUR" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

Also, we can attach a prefix or suffix with the prefix and suffix props:

<template>
  <div>
    <InputNumber v-model="value" prefix="Expires in " suffix=" days" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

We can also add buttons as addons for the numeric input with several props:

<template>
  <div>
    <InputNumber
      v-model="value"
      showButtons
      buttonLayout="horizontal"
      decrementButtonClass="p-button-danger"
      incrementButtonClass="p-button-success"
      incrementButtonIcon="pi pi-plus"
      decrementButtonIcon="pi pi-minus"
    />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

showButtons lets us show the buttons.

Then we set the classes and icons for the increase and decrease buttons.

Conclusion

We can add input masks and numeric inputs into our Vue 3 app with PrimeVue.

Categories
JavaScript Basics

Using Strings in JavaScript

Defining Strings

It can take a few forms, like in the following code:

'string'
`string`
'日本語'

These are called string literals. The first string is a normal string. The second one is a template string literal. They are primitive values and have the type ‘string’. We can also define strings with the String function, like in the following code:

String(1)

The code above would return '1' since we convert the number 1 into a string. This can be done with all primitive values, like in the following examples:

String(true)
String('string')
String(undefined)
String(null)
String(Symbol('a'))

If we log the code above line by line, we would get:

true
string
undefined
null
Symbol(a)

However, the String method doesn’t work very well with objects like in the following code:

const str = String({
  a: 1
});
console.log(str);

The code above will get us [object Object]. However, if an object has a toString() function, then we would get something useful when using the String function to convert it to a string. For example, if we have:

const str = String({
  a: 1,
  toString(){
   return JSON.stringify(this)
  }
});
console.log(str);

console.log(String([1, 2, 3]))
console.log(String(new Date()))

Then we get:

{"a":1}
1,2,3
Sun Oct 27 2019 10:30:54 GMT-0700 (Pacific Daylight Time)

As we can see, if we added a toString() method to an object then we can get a string representation of it with the String function. This is the same with arrays and the Date object, which both have the toString() method built-in.

If we have:

console.log([1, 2, 3].toString())
console.log(new Date().toString())

Then we get the same output as in the previous example.

Escape Characters

In addition to regular printable characters, strings can also have special characters that can be escaped. The following are the escape characters that can be added into strings:

  • XXX (XXX = 1 – 3 octal digits; range of 0 – 377) — ISO-8859-1 character / Unicode code point between U+0000 and U+00FF
  • ' — single-quote
  • " — double quote
  • “ —backslash
  • n —new line
  • r — carriage return
  • v — vertical tab
  • t — tab
  • b — backspace
  • f — form feed
  • uXXXX (XXXX = 4 hex digits; range of 0x0000 – 0xFFFF)UTF-16 code unit / Unicode code point between U+0000 and U+FFFF
  • u{X}u{XXXXXX} (X…XXXXXX = 1 – 6 hex digits; range of 0x0 – 0x10FFFF) UTF-32 code unit / Unicode code point between U+0000 and U+10FFFF
  • xXX (XX = 2 hex digits; range of 0x00 – 0xFF)ISO-8859-1 character / Unicode code point between U+0000 and U+00FF

Long strings can be concatenated together if they need to wrap into the next line with the + operator. For example, if we have a long string like the one below, we can write:

`let longString = "`Lorem ipsum dolor sit amet, consectetur `" +
                 "`adipiscing elit. Nulla nec facilisis libero, `" +
                 "`nec pulvinar est.`";`

More convenient ways to wrap long strings are using a slash character or use a string template literal. With the slash character, we can rewrite the string above with:

`let longString = "`Lorem ipsum dolor sit amet, consectetur   adipiscing elit. Nulla nec facilisis libero, `` nec pulvinar est.`";`

To write it with a template string, we can write:

let longString = `Lorem ipsum dolor sit amet, consectetur adipiscingelit. Nulla nec facilisis libero, nec pulvinar est.`;

Since spacing is preserved with template strings, we do not want to add extra spacing. Instead, we want to let it automatically wrap into the next line.

String Operations

We can access a character of a string by using the charAt method or using the bracket notation like accessing an entry in an array. To use the charAt method, we can write:

'dog'.charAt(1)

This would return ‘o’. Equivalently, we can use the bracket notation to get the same character as in the following code:

'dog'[1]

Which should get the same output when logged. We can’t delete or reassign a character with this notation since it’s not writable and its property descriptors can’t change, and it can’t be deleted.

To compare strings, we can use the normal comparison operators that we use like with anything else. For example, we can write:

console.log('a' < 'b');
console.log('a' > 'b');
console.log('a' == 'b');
console.log('a' === 'b');

The code above would get us:

true
false
false
false

The order is determined by the Unicode character code’s order in the list of characters or the collation specification depending on the locale. This means that the sort order may be different for different languages. String comparisons are case sensitive. For case insensitive comparisons, we have to convert them to the same case. For the best result, we should convert all the strings to uppercase since some Unicode characters don’t convert properly when converted to lowercase. For example, if we want to do case insensitive equality check then we can write:

console.log('abc'.toUpperCase() === 'Abc'.toUpperCase());

The code above would show true in the console.log .

In JavaScript, there’s also a string object, in addition to string literals. Strings can be defined with the String constructor by using the new String() constructor. With the String constructor, we get that the string will be type object even though everything else is the same. A string literal will have type string. For example, if we have the following code:

const sPrim = 'foo';
const sObj = new String(sPrim);
console.log(typeof sPrim);
console.log(typeof sObj);

The first console.log would show ‘string’ and the second one would show ‘object’. With the valueOf method, we can convert a string object into a primitive string. For example, we can write:

const sPrim = 'foo';
const sObj = new String(sPrim);
console.log(typeof sPrim);
console.log(typeof sObj.valueOf());

Then we get that both console.log statements would show ‘string’.

Basic Methods

To take full advantage of strings, we have to be able to manipulate them. Fortunately, strings have plenty of available methods to make manipulating them easy.

String.substr()

JavaScript strings have a substr function to get the substring of a string.

It takes a starting index as the first argument and a number of characters from the start index as the second argument.

It can be used like this:

const str = "Hello Bob";
const res = str.substr(1, 4); // ello

String.substring()

JavaScript strings also have a substring function that takes the start and end index as two arguments and returns a string with the ones between the start and end indices.

The start index is included but the end index is excluded.

Example:

const str = "Hello Bob";
const res = str.substring(1, 3); // el

String.toLocaleLowerCase()

Converts a string to lowercase, according to the locale of your browser. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";
const res = str.toLocaleLowerCase(); // hello bob!

String.toLocaleUpperCase()

Converts a string to uppercase, according to the locale of your browser. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";
const res = str.toLocaleUpperCase(); // 'HELLO BOB!'

String.toLowerCase()

Converts a string to lowercase. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";
const res = str.toLocaleLowerCase(); // 'hello bob!'

String.toUpperCase()

Converts a string to uppercase. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";
const res = str.toLocaleUpperCase(); // 'HELLO BOB!'

String.trim()

Remove starting and ending white space from a string.

For example:

const str = "         Hello Bob!     ";
const res = str.trim(); // 'Hello Bob!'

String.repeat()

To use the repeat function, you pass in the number of times you want to repeat the string as an argument. It returns a new string.

For example:

const hello = "hello";
const hello5 = A.repeat(5);
console.log(hello5); // "hellohellohellohellohello"

String.startsWith()

startsWith checks if a string starts with the substring you pass in.

For example:

const str = "Hello world.";
const hasHello = str.startsWith("Hello"); // trueconst str2 = "Hello world.";
const hasHello2 = str.startsWith("abc"); // false

String.endsWith()

endsWith checks if a string ends with the substring you pass in.

For example:

const str = "Hello world.";
const hasHello = str.endsWith("world."); // trueconst str2 = "Hello world.";
const hasHello2 = str.endsWith("abc"); // false

String.indexOf()

indexOf finds the index of the first occurrence of the substring. Returns -1 if not found.

For example:

const str = "Hello Hello.";
const hasHello = str.indexOf("Hello"); // 0
const hasHello2 = str.indexOf("abc"); // -1

String.lastIndexOf()

lastIndexOf finds the index of the last occurrence of the substring. Returns -1 if not found.

For example:

const str = "Hello Hello.";
const hasHello = str.lastIndexOf("Hello"); // 6
const hasHello2 = str.lastIndexOf("abc"); // -1

String.charAt()

charAt returns the character located at the index of the string.

For example:

const str = "Hello";
const res = str.charAt(0); // 'H'

String.search()

search gets the position of the substring passed into the function. It returns -1 if the substring is not found in the string.

Example:

const str = "Hello";
const res = str.search('H'); // 0

String.includes

includes checks if the passed-in substring is in the string. Returns true if it is in the string, false otherwise.

const str = "Hello";
const hasH = str.includes('H'); // true
const hasW = str.includes('W'); // false

String.replace()

The replace() function is useful for replacing parts of strings with another. It returns a new string with the string after the substring is replaced.

Example:

const str = "Hello Bob";
const res = str.replace("Bob", "James"); // 'Hello James'

replace() can also be used to replace all occurrences of a substring using the Regex g global property.

For example:

const str = "There are 2 chickens in fridge. I will eat chickens today.";
const res = str.replace(/chickens/g, "ducks"); // "There are 2 ducks in fridge. I will eat ducks today."

If the first argument is a regular expression that searches globally, it will replace all occurrences of the substring.

Strings are an important global object in JavaScript. It represents a sequence of characters. It can be used by various operators like comparison operators and it has methods that can manipulate them. Other important methods include searching of strings with the includes method and the indexOf method. They also have a trim() method to trim strings.

Categories
PrimeVue

Vue 3 Development with the PrimeVue Framework — Rich Text Editor Toolbar, Input Groups, and Input Masks

PrimeVue is a UI framework that’s compatible with Vue 3.

In this article, we’ll look at how to get started with developing Vue 3 apps with PrimeVue.

Rich Text Editor Toolbar Configuration

We can change the configuration of PrimeVue’s rich text editor’s toolbar by populating the toolbar slot:

<template>
  <div>
    <Editor v-model="value" editorStyle="height: 320px">
      <template #toolbar>
        <span class="ql-formats">
          <button class="ql-bold"></button>
          <button class="ql-italic"></button>
          <button class="ql-underline"></button>
        </span>
      </template>
    </Editor>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

We add buttons to let us set the text styles in the editor.

Input Group

We can add input groups by adding some classes provided by the PrimeVue framework.

For instance, we can write:

main.js

import { createApp } from "vue";
import App from "./App.vue";
import PrimeVue from "primevue/config";
import InputText from 'primevue/inputtext';
import 'primevue/resources/primevue.min.css'
import 'primevue/resources/themes/saga-blue/theme.css'
import 'primeicons/primeicons.css'
import 'primeflex/primeflex.css';

const app = createApp(App);
app.use(PrimeVue);
app.component("InputText", InputText);
app.mount("#app");

App.vue

<template>
  <div>
    <div class="p-col-12 p-md-4">
      <div class="p-inputgroup">
        <span class="p-inputgroup-addon">
          <i class="pi pi-user"></i>
        </span>
        <InputText placeholder="Username" />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

We register the InputText component in main.js .

Then we add the p-inputgroup class to make the div an input group container.

The p-inputgroup-addon class lets us attach items to the input group’s input.

We can also add it to the right side:

<template>
  <div>
    <div class="p-col-12 p-md-4">
      <div class="p-inputgroup">
        <InputText placeholder="Username" />
        <span class="p-inputgroup-addon">
          <i class="pi pi-user"></i>
        </span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

We can also add a checkbox as an input group addon by writing:

main.js

import { createApp } from "vue";
import App from "./App.vue";
import PrimeVue from "primevue/config";
import InputText from 'primevue/inputtext';
import Checkbox from 'primevue/checkbox';
import 'primevue/resources/primevue.min.css'
import 'primevue/resources/themes/saga-blue/theme.css'
import 'primeicons/primeicons.css'
import 'primeflex/primeflex.css';

const app = createApp(App);
app.use(PrimeVue);
app.component("InputText", InputText);
app.component("Checkbox", Checkbox);
app.mount("#app");

App.vue

<template>
  <div>
    <div class="p-col-12 p-md-4">
      <div class="p-inputgroup">
        <span class="p-inputgroup-addon">
          <Checkbox v-model="checked" binary />
        </span>
        <InputText placeholder="Username" />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      checked: false,
    };
  },
  methods: {},
};
</script>

We add the Checkbox into the span with the p-inputgroup-addon class.

Input Mask

PrimeVue comes with the InputMask component to let us add an input mask into our Vue 3 app.

For example, we can write:

main.js

import { createApp } from "vue";
import App from "./App.vue";
import PrimeVue from "primevue/config";
import InputMask from 'primevue/inputmask';
import 'primevue/resources/primevue.min.css'
import 'primevue/resources/themes/saga-blue/theme.css'
import 'primeicons/primeicons.css'
import 'primeflex/primeflex.css';

const app = createApp(App);
app.use(PrimeVue);
app.component("InputMask", InputMask);
app.mount("#app");

App.vue

<template>
  <div>
    <InputMask v-model="value" mask="a*-999-a999" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: "",
    };
  },
  methods: {},
};
</script>

to register and add the InputMask component.

The mask prop specifies the format that the input can accept.

We bind the entered value to the value reactive property with v-model .

Conclusion

We can add a rich text editor with a custom toolbar, input groups and input masks with PrimeVue.