vue.js - 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 机制却没有赶上?
解决方案
您的颜色不是反应性的,因为您将其设置为 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);
);
},
},
}
推荐阅读
- python - ModuleNotFoundError:当我通过 virtualenv 创建新环境时,没有名为“virtualenv.seed.embed.via_app_data”的模块
- javascript - 更改列表顶部的 Django 水平滚动
- php - 如何在雄辩的关系laravel中从复选框值显示多个类别名称
- python - 如何从二维列表中删除第一列?
- regex - 为什么这个正则表达式匹配只显示捕获变量中的第一个单词,而不是整行?
- ruby-on-rails - mysql2 Ruby Gem 无法安装 ubuntu 20.04
- php - Laravel 显示简单的 500 错误(没有 Whoops 或 Ignition)
- pandas - 如何在python中将数据添加到现有的excel文件而不覆盖数据
- reactjs - 如何知道功能组件中的“子”道具组件类型?
- java - 填写表格时PDFBox嵌入字体不起作用