How to translate component attributes/properties using Vue I18n
P粉416996828
P粉416996828 2023-11-07 12:47:10
0
2
677

How to translate the incoming properties/properties of a component? For example, I have a card component with title and description properties defined.


<!-- my-card  组件 -->
    <template>
      <div>
        <h2>{{title}}</h2>
        <span>{{description}}</span>
      </div>
    </template>

    <script>
      export default {
        props: {
          title: String,
          descritpion: String
        }
      }
    </script>


Then use the my-card component in another page/component as shown below


  

  <template>
      <div>

        <header>页面头部</header>
        <my-card :title="最好的卡片标题" :description="最好的描述" />
        <footer>页面底部</footer>
      </div>
    </template>


How to use vue I18n to translate component properties?


  

  <template>
      <div>

        <header>页面头部</header>
        <my-card :title="{{ $t('myCard.title')}}" :description="{{$t('myCard.description')}}" />
        <footer>页面底部</footer>
      </div>
    </template>


I can't seem to get the incoming attribute translation to work.

P.S. I know I can add translations where the my-card component is defined, but the problem here is that the component is a third party component from the NPM library.

I know some packages in React.js have this functionality.

P粉416996828
P粉416996828

reply all(2)
P粉447002127

You can use I18n translation in component properties as shown below.

<my-card 
:title="$t('myCard.title')"
:description="$t('myCard.description')" 
/>
P粉447785031

Just bind the translation without using {{}}:

<my-card :title="$t('myCard.title')" :description="$t('myCard.description')" />
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template