当我更改数据时,计算出的数据不会立即改变

时间:2018-04-06 04:36:24

标签: vue.js

我有一个Vue.js演示,请看下面的文字:

<template>
  <div class="index">

    <Row>
      <Select  v-for="(select, s_index) in select_data" v-model="selected_data_obj[s_index]" :key="'s-'+s_index" style="width:200px">
        <Option v-for="option in option_data[s_index]" :key="option.value" :value="option.value"></Option>
      </Select>

    </Row>

    <Row>
      <Button type="warning" @click="add_select_data">Add option</Button>
    </Row>
  </div>
</template>
<script>


  export default {
    data(){
      return {
        select_data:[{},{}],
        selected_data_obj : {

        },
//        option_data:  {
//          0: [{value:'a'}, {value:'b'}, {value:'c'}, {value:'d'}, {value:'e'}],
//          1: [{value:'a'}, {value:'b'}, {value:'c'}, {value:'d'}, {value:'e'}]
//        }
      }
    },
    computed: {
      option_data(){
        return {
          0: [{value:'a'}, {value:'b'}, {value:'c'}, {value:'d'}, {value:'e'}],
          1: [{value:'a'}, {value:'b'}, {value:'c'}, {value:'d'}, {value:'e'}]
        }
      }
    }
    ,
    methods: {
      add_select_data(){
        console.log('click')
        this.option_data["0"].push({value:'f'})
      }
    },

  };
</script>

我使用“添加”选项按钮为option_data添加数据。

我将option_data放在计算方法中,但是如果我单击Add option,它不会刷新该选项,您会看到以下快照:

enter image description here

但是,如果我将option_data放在data中,您会在我的代码中看到该组件。不会有这个问题。

我该如何解决这个问题?如果我必须将option_data放入计算方法中?

1 个答案:

答案 0 :(得分:0)

默认情况下,计算属性仅是getter的,因此您应该提供setter。More information about getter and setter

您可以在此处更改代码:

export default {
    data(){
      return {
        select_data:[{},{}],
        selected_data_obj : {

        },
        option_data:  {
          0: [{value:'a'}, {value:'b'}, {value:'c'}, {value:'d'}, {value:'e'}],
          1: [{value:'a'}, {value:'b'}, {value:'c'}, {value:'d'}, {value:'e'}]
        }
      }
    },
    methods: {
      add_select_data(){
        console.log('click')
        this.option_data["0"].push({value:'f'})
      }
    },
  };