让 VueI18n 对路由器 link 标签做出反应

Make VueI18n react to router link tag

我有这个 Vue 应用程序,它由一个简单的主页、一个标题和一个主页文本组成。您可以在我的 JSFiddle 上在线查看此应用程序。这是代码:

HTML

<div id="app">
  My header app
  <router-view></router-view>
</div>

JavaScript

const Home = {
    template: `
      <div>
        <h1>{{ $t('home.title') }}</h1>
        <p v-html="$t('home.text')"></p>
      </div>
    `
};

const messages = {
    en: {
    home: {
        title: 'Hello world',
        text: 'Find all post by clicking <router-link to="/post">this link</router-link>!'
    }
  }
};

const routes = [
    { name: 'home', path: '*', component: Home }
];

const i18n = new VueI18n({
    locale: 'en',
    fallbackLocale: 'en',
    messages: messages
});

const router = new VueRouter({
    mode: 'history',
    routes: routes
});

const vue = new Vue({
    el: '#app',
    router: router,
    i18n: i18n
});

问题

如您所见,没有 "router-link" link 可见,单击 link 将不会重定向到所需的路线。

问题

是否可以让 VueI18n 在 v-html 指令中解释 <router-link> 标签?

v-htmlplain HTML 替换元素的内容,因此替换字符串中使用的自定义元素不会编译为 Vue.js 组件。

您可能需要查看 VueI18n documentation 建议的组件插值方式,其中涉及 i18n 功能组件和模板字符串的使用。

这是实现此方法的 fiddle 的分支:http://jsfiddle.net/u5vx1mLq/

简而言之,i18n 组件有 path 属性,您可以在其中设置模板字符串的路径和 tag 定义标签的属性,i18n 组件是为了被替换为。 i18n 也有一个插槽,可用于定义一个子组件,您可以在其中插入模板字符串的部分内容。

抱歉解释不当,希望代码片段能对此事有所启发:

const Home = {
  template: `
    <div>
      <h1>{{ $t('home.title') }}</h1>
      <i18n path="home.linkLabel" tag="label" for="home.linkText">
        <router-link to="/post">{{ $t('home.linkText') }}</router-link>
      </i18n>
    </div>
  `
};

const messages = {
  en: {
    home: {
      title: 'Hello world',
      linkText: 'this link',
      linkLabel: 'Find all post by clicking {0}'
    }
  }
};