vue.js - VueJs - 在方法之间传递变量

标签 vue.js vuejs2 reactive vuetify.js vue-chartjs

有一个 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" 相同。这就是你想要的。

See demo JSFiddle here .


自动更新vue-chartjsBarChartlabel

虽然你是

图表不会自动反射(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.vuechangeLabelAndReassign() 方法)。

关于vue.js - VueJs - 在方法之间传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49027373/

相关文章:

vue.js - VueJS - SSR - 在渲染之前等待创建的() Hook 中的异步数据

javascript - Vue.js,将值从组件发送到 router/index.js

vue.js - 在div vuejs中添加HTML元素

javascript - 如何将搜索查询框合并到 Vue.js 中的 api 调用中

spring-boot - 响应式(Reactive)编程 : Spring WebFlux: How to build a chain of micro-service calls?

javascript - 在 vue 中渲染组件上的 this.$refs.xx 或 this.$el 上未定义

javascript - 如何使用 Vue JS-axios 在 POST api 中传递 Header + Body

angular - 通过formControlName添加CSS类

javascript - Vuetify - 如何访问表单规则中的数据

java - 我们必须在 WebFlux 中编写响应式代码吗?