'VUE2js: How to have component re-render after its props change?
a Vue newbie here. The thing is is simple:
<template>
<btn :color="color" @click="toggleColor">{{btnmsg}}</btn>
</template>
<script>
import { Btn } from 'chico'
export default = {
name: 'AButton',
componenents: {
Btn
},
data () {
return {
btnmsg: 'Legia pany'
colors: ['blue', 'black', 'green', 'organge', 'teal', 'cyan', 'yellow', 'white'],
color: 'red'
}
},
methods: {
toggleColor () {
this.color = this.colors[Math.floor(Math.random() * Math.floor(this.colors.length))]
}
}
</script>
The 'Btn' from the ChicoFamily goes something like this
<template>
<button :is="tag" :class="[className, {'active': active}]" :type="type" :role="role" ">
<slot></slot>
</button>
</template>
<script>
import classNames from 'classnames';
export default {
props: {
tag: {
type: String,
default: "button"
},
color: {
type: String,
default: "default"
...it takes hellotta props...
},
data () {
return {
className: classNames(
this.floating ? 'btn-floating' : 'btn',
this.outline ? 'btn-outline-' + this.outline : this.flat ? 'btn-flat' : this.transparent ? '' : 'btn-' + this.color,
...classes derived from these props...
)
};
}
};
</script>
Yes, it is a button that, when clicked, should change its color. Clicking it indeed changes a prop passed, but does not, in fact, have the button re-rendered. I am asking this question, because I feel like there is something bigger about Vue2 mechanics that is eluding me.
Why passing a different prop does not re-render this sweet-baby-to-be button? How does one do it properly?
Best, Paco
[edit:] The Btn takes its color from Bootstrap classes deriving from the prop. Can it be that it gets the proper props in, but the className mechanic does not catch up?
Solution 1:[1]
Setting a :key on the component is the best way to force Vue to re-render the component. If you require the component to be re-rendered, simply modify the value of the key, and Vue will re-render it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fotiecodes |
