首页 文章

VueJs - 在方法之间传递变量

提问于
浏览
1

有一个 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>

1 回答

  • 2

    在Inside方法中,您可以使用 this 引用 data 属性 .

    在您的情况下,您可以使用 this.datacollection.datasets.label 并分配给它:

    methods: {
      // ...
      fillData(selected){
         this.datacollection.datasets[0].label = selected;
      },
    }
    

    当然,这假设 selected 是您要分配给 label 的字符串 .

    Note: this 仅在使用 methodName() {} (按原样)或 methodName: function (){... 声明方法时有效 . 所以don't use arrow functions when declaring vue methods,他们会弄乱你的 this .

    使用@(v-on)绑定到事件而不是:v-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-chartjs的BarChart标签

    即使你是

    图表不会自动反映更改(标签不会更改) .

    我注意到这是因为 the chart only reacts to whole datacollection 更改,而不是内部属性(如 label ) .

    所以解决方案是:

    • "clone" datacollection

    • 更新克隆的 label

    • 将克隆分配给 this.datacollection

    并且图表将作出反应(标签更改将被反映) .

    因此,将 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() 方法) .

相关问题