Is there a way to use previous answers in inquirer

2019-06-26 02:58发布

问题:

So what I want to do is use a previous answer when asking a question further down the line. Basically so that I can show a summary of what will be created and ask for a verification.

this.prompt([   
    {
      type: 'input',
      name: 'name',
      message: 'What is your name?'
      default: 'Jake'
    },
    {
      type: 'confirm',
      name: 'summary',
      message: 'Is this information correct? Your name is:' + answers.name',
    }

is there an easy way to achieve this? Or another way to achieve a summary type thing that lists out all previous answers?

回答1:

Either nest inquirer calls:

inquirer
  .prompt({
    type: 'list',
    name: 'chocolate',
    message: "What's your favorite chocolate?",
    choices: ['Mars', 'Oh Henry', 'Hershey']
  })
  .then(() => {
    inquirer.prompt({
      type: 'list',
      name: 'beverage',
      message: 'And your favorite beverage?',
      choices: ['Pepsi', 'Coke', '7up', 'Mountain Dew', 'Red Bull']
    });
  });

Or use the when function.

{
  type: 'confirm',
  name: 'summary',
  message: 'Is this information correct? Your name is:' + answers.name',
  when: function( answers ) {
    // Only run if user set a name
    return !!answers.name;
  },
}