Skip to content

Problem with translations not updating when using v-if #29

@kennyki

Description

@kennyki

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?

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions