首页 > 解决方案 > VUE2js:如何在其道具更改后重新渲染组件?

问题描述

这里是 Vue 新手。事情很简单:

<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>

ChicoFamily 的“Btn”是这样的

  <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>

是的,它是一个按钮,单击时应更改其颜色。单击它确实会更改传递的道具,但实际上并没有重新渲染按钮。我问这个问题是因为我觉得 Vue2 的机制有一些更大的东西在逃避我。

为什么传递不同的道具不会重新渲染这个可爱的宝贝按钮?如何正确地做到这一点?

最好的,帕科

[编辑:] Btn 的颜色来自从 prop 派生的 Bootstrap 类。会不会是它获得了正确的道具,但 className 机制却没有赶上?

标签: vue.jsvuejs2vue-component

解决方案


您的颜色不是反应性的,因为您将其设置为 adata而不是 a computed

按照您的操作方式,className将在创建实例时设置一次。

为了在className每次更改 state 中的一个道具时进行重新评估,您必须从中做出一个computed property

Btn 组件:

export default {
  props: {
    [...]
  },
  computed: {
    className() {
      return classNames(
        this.floating ? 'btn-floating' : 'btn',
        this.outline ? 'btn-outline-' + this.outline : this.flat ? 'btn-flat' :   this.transparent ? '' : 'btn-' + this.color);
      );
    },
  },
}

推荐阅读