【问题标题】:VUE2js: How to have component re-render after its props change?VUE2js:如何在其道具更改后重新渲染组件?
【发布时间】:2018-10-08 04:13:04
【问题描述】:

这里是 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 机制中有一些更大的东西让我无法理解。

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

最好的,帕科

[edit:] Btn 的颜色来自从 prop 派生的 Bootstrap 类。难道是它获得了适当的道具,但className机制没有赶上?

【问题讨论】:

  • 您要导入的chicoBtn 组件是什么?
  • 为它添加了一些代码!如您所见,它是一个按钮的包装器,其中包含许多用于正确样式的道具

标签: vue.js vuejs2 vue-component


【解决方案1】:

您的颜色没有反应,因为您将其设置为 data 而不是 computed

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

为了让className 在每次更改状态中的一个道具时重新评估,您必须从中创建一个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);
      );
    },
  },
}

【讨论】:

    猜你喜欢
    • 2020-12-24
    • 2019-10-31
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多