首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基于Base64和Nuxt.js的Nuxt.js编码/解码

基于Base64和Nuxt.js的Nuxt.js编码/解码
EN

Stack Overflow用户
提问于 2021-06-30 10:23:26
回答 1查看 1.1K关注 0票数 0

是否有一种简单的方法可以在Base64中对Nuxt.js中的字符串进行编码/解码,同时支持服务器端呈现,最好是TypeScript?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-30 10:23:26

没有内置的方法,我也没有找到任何插件,所以我自己创建了一个很小的插件,可以简单地放到/plugins目录中。

代码语言:javascript
运行
复制
import { Plugin } from '@nuxt/types'

function encodeBase64 (value: string): string {
  if (process.client) {
    return window.btoa(unescape(encodeURIComponent(value)))
  } else {
    return Buffer.from(value, 'ascii').toString('base64')
  }
}

function decodeBase64 (value: string): string {
  if (process.client) {
    return decodeURIComponent(escape(window.atob(value)))
  } else {
    return Buffer.from(value, 'base64').toString('ascii')
  }
}

declare module 'vue/types/vue' {
  interface Vue {
    $encodeBase64: (value: string) => string,
    $decodeBase64: (value: string) => string
  }
}

declare module '@nuxt/types' {
  // nuxtContext.app.$lines inside asyncData, fetch, plugins, middleware, nuxtServerInit
  interface NuxtAppOptions {
    $encodeBase64: (value: string) => string,
    $decodeBase64: (value: string) => string
  }
  // nuxtContext.$lines
  interface Context {
    $encodeBase64: (value: string) => string,
    $decodeBase64: (value: string) => string
  }
}

declare module 'vuex/types/index' {
  // this.$lines inside Vuex stores
  // eslint-disable-next-line
  interface Store<S> {
    $encodeBase64: (value: string) => string,
    $decodeBase64: (value: string) => string
  }
}

const base64Plugin: Plugin = (_context, inject) => {
  inject('encodeBase64', encodeBase64)
  inject('decodeBase64', decodeBase64)
}

export default base64Plugin

不要忘记将它加载到您的nuxt.config.ts

代码语言:javascript
运行
复制
  plugins: [
    { src: '~/plugins/base64.ts' },
  ],

现在,在客户端和服务器端的$encodeBase64()组件中使用$decodeBase64()$decodeBase64()

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68192978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档