【问题标题】:Base64 encoding/decoding in Nuxt.js with TypeScript and SSR使用 TypeScript 和 SSR 在 Nuxt.js 中进行 Base64 编码/解码
【发布时间】:2021-06-30 10:23:26
【问题描述】:

是否有一种简单的方法可以在 Nuxt.js 中将字符串编码/解码到 Base64 或从 Base64 解码,并支持服务器端渲染,最好是 TypeScript?

【问题讨论】:

    标签: nuxt.js


    【解决方案1】:

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

    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:

      plugins: [
        { src: '~/plugins/base64.ts' },
      ],
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 1970-01-01
      • 2023-03-16
      • 2016-05-28
      • 1970-01-01
      相关资源
      最近更新 更多