How do I programmatically create a view in a custom module?
Place the YAML file in config/optional as you would normally do to create the view on install optionally when Views is enabled.

Then use an update hook to check whether the view exists when updating the module and create it in PHP by reading the YAML file:

function dblog_post_update_convert_recent_messages_to_view() {

  // Only create if the views module is enabled and the watchdog view doesn't
  // exist.
  if (\Drupal::moduleHandler()
    -&gt;moduleExists('views')) {
    if (!View::load('watchdog')) {

      // Save the watchdog view to config.
      $module_handler = \Drupal::moduleHandler();
      $optional_install_path = $module_handler
        -&gt;getModule('dblog')
        -&gt;getPath() . '/' . InstallStorage::CONFIG_OPTIONAL_DIRECTORY;
      $storage = new FileStorage($optional_install_path);
      \Drupal::entityTypeManager()
        -&gt;getStorage('view')
        -&gt;create($storage
        -&gt;read('views.view.watchdog'))
        -&gt;save();
      return t('The watchdog view has been created.');
    }
    return t("The watchdog view already exists and was not replaced. To replace the 'Recent log messages' with a view, rename the watchdog view and uninstall and install the 'Database Log' module");
  }
}


Source: dblog_post_update_convert_recent_messages_to_view