I want to configure Sweetalert2 modal in such a way in which I am able to select different options from a list. This was easily achieved using the following code:

swal({
  title: 'Select Outage Tier',
  input: 'select',
  inputOptions: {
    '1': 'Tier 1',
    '2': 'Tier 2',
    '3': 'Tier 3'
  },
  inputPlaceholder: 'required',
  showCancelButton: true,
  inputValidator: function (value) {
    return new Promise(function (resolve, reject) {
      if (value !== '') {
        resolve();
      } else {
        reject('You need to select a Tier');
      }
    });
  }
}).then(function (result) {
  if (result.value) {
    swal({
      type: 'success',
      html: 'You selected: ' + result.value
    });
  }
});

It was copied from a different question and it worked like a charm for the first part of my project. I can add new options in the inputOptions: {} tag. However, I want to display the options dynamically without having to change the code manually every time add/remove one.

I am retrieving the options from a database, by calling an API. This part was also done quickly and it works pretty well. I retrieve the data and store in a variable options: ''. The data is stored and ready to be used with the above code.

HERE COMES THE PROBLEM: I am still pretty new to VueJS and all I can do for now is basic coding. I tried to use a code snippet, from my own project, inside the inputOptions: {} tag, hoping it will work in the same way it works inside a method:

  inputOptions: {
   this.options.forEach((option) => {
      option.id : option:name
    });
  },

However, it doesn't work at all. I get an error Uncaught SyntaxError: Unexpected token . on the second line of the snippet code above.

All I want to do is to retrieve and display the options, from the database, inside the Sweetalert2 modal. Is there an easier, more efficient way to do so?

1 Answers

2
ittus On Best Solutions

You can use computed property to prepare data for inputOptions

computed: {
  optionsDict() {
     if (!this.options) return {}
     return this.options.reduce((a, c) => {
      a[c.id] = c.name
      return a
     }, {})
  }
}

and then

swal({
  ...
  inputOptions: this.optionsDict
  ...
})