Home > Net >  Vue doesnt update component on dynamic variable condition change
Vue doesnt update component on dynamic variable condition change

Time:10-07

I am working with Vuejs. I want to render components based on value of variable val. My component looks like this

<template v-if="this.$val===1">
    <component1 />
 </template>
<template v-if="this.$val===2">
    <component2 />
</template>

I have defined a global variable val using Vue.prototype and I am updating it using onclick function,where I am changing value of val to 2 but after clicking it doesnt show component2 instead of component 1. Define val globally in main.js using following line of code

Vue.prototype.$val = 1;

Can someone please help me with this. Thanks

CodePudding user response:

global variables are accessed in template without this keyword which means $val===1 will work.

Solution 1:

<template>
 <component1 v-if='$val === 1' />
 <component2 v-else/>
</template>

This will work.

But you could make use of dynamic components in your case.

Solution 2:

<template>
    <component :is='currentComponent'/>
</template>

<script>
\\imports of your components will go here
export default {
  name: 'app',
  components: {
    component1, component2
  },
  computed:{
    currentComponent(){
      return this.$val === 1?component1:component2;
    }
  }
}
</script>

You don't have to repeat template for if conditions as you did in question.

Dynamic components are more performant and helps you maintain state of component.

CodePudding user response:

Usually u just use variablename not this.variablename in the template.

  • Related