Polyconseil/vue-gettext

Problem with translations not updating when using v-if

kennyki opened this issue · 4 comments

Stumbled upon this issue with v-if on the v-translate directive in my project, however the same issue can be replicated with the translate directive.

In the component spec, try:

it('supports conditional rendering such as v-if, v-else-if, v-else', (done) => {
    Vue.config.language = 'en_US'
    let vm = new Vue({
      template: `
      <translate v-if="show">Pending</translate>
      <translate v-else>Hello %{ name }</translate>
      `,
      data: {show: true, name: 'John Doe'},
    }).$mount()
    expect(vm.$el.innerHTML).to.equal('Pending')
    console.log(vm.$el)
    vm.show = false
    vm.$nextTick(function () {
      expect(vm.$el.innerHTML).to.equal('Hello John Doe')
      done()
    })
  })

It will output:

ERROR: AssertionError{message: 'expected 'Pending' to equal 'Hello John Doe'', showDiff: true, actual: 'Pending', expected: 'Hello John Doe',

Root cause

It is because of:

The key special attribute is primarily used as a hint for Vue’s virtual DOM algorithm to identify VNodes when diffing ... Vue uses an algorithm that minimizes element movement and tries to patch/reuse elements of the same type in-place as much as possible.

as explained in the section of special attribute 'key'

Solution 1

Add key attribute manually to translate or v-translate

<translate key="1" v-if="show">Pending</translate>
<translate key="2" v-else>Hello %{ name }</translate>

This is the immediate fix for anyone having this issue.

However this is not really ideal because we need to ensure that the keys are unique within each v-if block.

Solution 2

Improve translate and v-translate to auto-generate key attribute if it's not present. I'll be looking at this, need to find a good way to generate unique keys.

Any idea?

kemar commented

@kennyki excellent work, thanx!

A good way to generate a unique key is to use a uuid, something like that https://gist.github.com/jcxplorer/823878

Sure @kemar. Will work on it soon.

kemar commented

Thank you very much @kennyki :)

Glad that I could help :-)