In this article, we will learn how to use cryptojs in vue.js
Step 1: Create a new Vue project:
vue create vue-cryptojs-demo
Step 2: Install require packages:
npm i vue-cryptojs
Step 3: Open main.js file and add following in it:
import { createApp } from 'vue' import App from './App.vue' import VueCryptojs from 'vue-cryptojs' createApp(App).use(VueCryptojs).mount('#app')
Step 4: Open App.vue file and add following in it:
<template> <input v-model="pvtData" placeholder="Enter a string" /> <button @click="encryptData">Encrypt</button> <button @click="decryptData">Decrypt</button> <button @click="deleteData">Delete</button> <p v-if="encData">Encrypt Data: {{ encData }}</p> <p v-if="decData">Decrypt Data: {{ decData }}</p> </template> <script> export default { name: 'App', data() { return { pvtData: "", secret: "123#$%", encData: "", decData:"" }; }, methods: { encryptData() { if (this.pvtData.length) { const data = this.$CryptoJS.AES.encrypt(this.pvtData, this.secret).toString(); localStorage.setItem("secretData", data); this.getEncryptedData(); } }, decryptData() { const secretData = localStorage.getItem("secretData"); const decryptData = this.$CryptoJS.AES.decrypt( secretData, this.secret ).toString(this.$CryptoJS.enc.Utf8); this.decData = decryptData; }, deleteData() { localStorage.removeItem("secretData"); this.decData = ""; this.getEncryptedData(); this.encData = ""; this.pvtData = ""; }, getEncryptedData() { this.encData = localStorage.getItem("secretData") || "Value not availbale"; }, }, } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
Code in Action: