有一个 v-select
组件,在更改时我启动了 fillData(selected)
,其中选中的是 v-model
。我需要在更改时更新 datacollection.datasets.label
中的标签。我该怎么做?
<script>
import BarChart from './BarChart.js'
import { mapGetters, mapActions } from "vuex";
export default {
name : "TestLegPerformance",
components: {
BarChart
},
data: () => ({
datacollection : {
labels: ['Week-1','Week-2','Week-3'],
datasets: [
{
label: '',
backgroundColor: '#C58917',
data: [40, 50, 20]
}
]
},
selected: []
}),
computed: {
...mapGetters({
planNames: "planNames"
})
},
mounted () {
this.getAllPlanNamesAction();
},
methods: {
...mapActions(["getAllPlanNamesAction"]),
fillData(selected){
console.log(selected)
},
}
}
</script>
最佳答案
在方法内部,您可以使用 this
引用 data
属性。
在您的情况下,您可以使用 this.datacollection.datasets.label
并分配给它:
methods: {
// ...
fillData(selected){
this.datacollection.datasets[0].label = selected;
},
}
当然,这假设 selected
是您要分配给 label
的字符串。
注意:this
仅在您使用 methodName() {}
(如您所愿)或 methodName: function (){...
.所以don't use arrow functions when declaring vue methods ,他们会弄乱你的this
。
使用 @
(v-on
) 而非 :
v-bind
) 绑定(bind)到事件
您的模板:
<v-select label="Select a Plan" :items="planNames" v-model="selected" single-line max-height="auto" :change="fillData(selected)" required >
要监听更改事件,请不要使用:
:change="fillData(selected)"
使用
@change="fillData"
不要发送参数(它会把事情搞砸)。 v-select
会发送给您一个。
请注意将 :
替换为 @
。
第一个,:
是v-bind
的别名。所以 :change="xyz"
与 v-bind:change="xyz"
相同。
第二个,@
是 v-on
的别名。所以 @change="xyz"
与 v-on:change="xyz"
相同。这就是你想要的。
自动更新vue-chartjs
的BarChart
的label
虽然你是
- using the
reactiveProp
mixin ;和 - 更改标签
图表不会自动反射(reflect)更改(标签不会更改)。
我注意到发生这种情况是因为图表仅对整个datacollection
更改使用react,而不是对内部属性(如label
)使用react。
所以解决方案是:
- “克隆”
数据收集
- 更新克隆的
标签
- 将克隆分配给
this.datacollection
图表会使用react(标签更改会反射(reflect)出来)。
因此,将您的 fillData
方法更改为以下内容:
fillData(selected){
let collectionClone = Object.assign({}, this.datacollection);
collectionClone.datasets[0].label = selected;
this.datacollection = collectionClone;
},
检查 here a working DEMO CODESANDBOX of this solution (参见 BarChart.vue
的 changeLabelAndReassign()
方法)。
关于vue.js - VueJs - 在方法之间传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49027373/