VUE-META 다국어 처리

SunnyMoon·2022년 8월 4일
1

vue-i18next을 이용하여 다국어처리를 할때, meta태그 설정

Vue3 를 사용해서 meta tag를 설정하는 방법

  1. 설치
npm install vue-meta@alpha // npm
yarn add vue-meta@alpha // yarn
  1. main.js 에 meta 에 관한 내용을 추가한다
  • 삽질을 해가면서 한것이라 필요 없는 내용을 불러올수도 있다 - 추후에 수정
import { createMetaManager, defaultConfig, resolveOption, useMeta, plugin as metaPlugin } from 'vue-meta'

const decisionMaker5000000 = resolveOption((prevValue, context) => {
  const { uid = 0 } = context.vm || {}
  if (!prevValue || prevValue < uid) {
    return uid
  }
})

const metaManager = createMetaManager({
  ...defaultConfig,
  esi: {
    group: true,
    namespaced: true,
    attributes: ['src', 'test', 'text']
  }
}, decisionMaker5000000)

useMeta(
  {
    og: {
      something: 'test'
    }
  },
  metaManager
)

app.use(createMetaManager()).use(metaPlugin).use(store).use(router).mount('#app')
  1. App.vue에 내용을 추가
  • 다국어 처리를 하기 때문에 i18next 로 값을 불러온것을 넣어주었다.
  • htmlAttrs 의 lang값을 처리하는 방식은 로컬에 저장된 i18nextLang에 대한 값을 넣어주었다
  • useMeta의 경우 setup() 에서 설정을 하라는 경우가 많았는데, i18next로 다국어를 설정할때 setUp()에서 감지를 못하는 경우가 생겨서 mount에 넣어서 처리를 했다. useMeta를 설정할때 꼭 setup에서 할 필요는 없다
  • setup의 경우 vue3에서 새로 추가된 문법이다
import { useMeta } from 'vue-meta'

<template>
  <div class="wrap">
  </div>
  <metainfo/>
</template>

export default {
  async setup () {
    await i18nextPromise
    return {}
  },
  mounted () {
    useMeta( // meta값 생성
      {
        title: i18next.t('meta.title'),
        titleTemplate: `%s${i18next.t('meta.title-template')}`,
        htmlAttrs: {
          lang: localStorage.getItem('i18nextLng')
        },
        meta: [
          {
            name: 'robots',
            content: 'index,follow'
          },
          {
            vmid: 'description',
            content: i18next.t('meta.main-description')
          },
          {
            hid: 'keywords',
            name: 'keywords',
            vmid: 'keywords',
            content: i18next.t('meta.main-keywords')
          }
        ]
      }
    )
  },
</script>
  1. vue.config.js
  • vue.config.js에 vue-meta에 관한것을 추가
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: ['vue-meta'],
})
  • useMeta의 값을 module로 빼서 사용할 수도 있었으나. 다국어를 3개밖에 지원하지 않았고, 많이 바뀌는 내용들이 없어서 App.vue에 넣어서 진행을 했다. 또한 i18next의 값이 변하기 위해서는 컴포넌트 안에서 처리가 되는것이 제일 오류가 적게 일어나 문제가 덜 일어났다
profile
프론트앤드 개발을 공부하는 중입니다:)

0개의 댓글