[Vuejs]-Reset a const variable to its default value in vue

0๐Ÿ‘

  1. Move the constant out of data.
  2. During reset, youโ€™ve reassign the default headercbo value with the constant value.
const _hdrList = [
            {
               label: 'start_time',
               value: 'start_time'
            },            
            {
               label: 'name',
               value: 'name'
            },
            {
               label: 'another',
               value: 'another'
            },
        ];
        const _cboList = [
            {start_time:''},
            {name:''},
            {another:''},
        ];
    
    export default {
    data(){
        return{
            hdrList:_hdrList,
            headercbo:_cboList,
            columns:[],
        }
    },
    clearFields() {
      this.columns = [];
      this.headercbo = _cboList;
    }
    }

0๐Ÿ‘

Put what you have in your data function into a method named initialData, then use that function in your data function and in your clearFields method.

  data() {
    return this.initialData();
  },
  methods: {
    initialData() {
      const _hdrList = [{
          label: 'start_time',
          value: 'start_time'
        },
        {
          label: 'name',
          value: 'name'
        },
        {
          label: 'another',
          value: 'another'
        },
      ];
      const _cboList = [{
          start_time: ''
        },
        {
          name: ''
        },
        {
          another: ''
        },
      ];
      return {
        hdrList: _hdrList,
        headercbo: _cboList,
        columns: [1,2],
      }
    },
    clearFields() {
      this.columns = [];
      this.headercbo = this.initialData().headercbo;
    }
  }

Leave a comment