在utils文件夹中新建utils.js
import CryptoJS from 'crypto-js'
const key = CryptoJS.enc.Utf8.parse("1234567890000000");
const iv = CryptoJS.enc.Utf8.parse("1234567890000000");
export default (app,inject) => {
inject('encrypt',word=>{
let encrypted = "";
if (typeof word == "string") {
encrypted = CryptoJS.AES.encrypt(word, key, { iv: iv }).toString()
} else if (typeof word == "object") {
const data = JSON.stringify(word);
encrypted = CryptoJS.AES.encrypt(data, key, { iv: iv }).toString()
}
return encrypted;
})
inject('decrypt',word=>{
const decryptedStr = CryptoJS.AES.decrypt(word, key, { iv: iv }).toString(CryptoJS.enc.Utf8)
return decryptedStr.toString();
})
}
在nuxt.config.js中引入
export default {
plugins: [
'@/utils/utils',
],
}
组件中使用:
export default{
//在asyncData中使用
asyncData(app){
//加密
const str = app.$encrypt('123455')
//解密
const str2 = app.$decrypt(str)
},
//在methods中使用的话可以直接通过this.$encrypt和this.$decrypt进行加解密
}