Vue2中如何通过代码触发@aws-amplify/ui-components的Toast组件
Got it, let's get that error toast working in your Vue 2 component using the deprecated @aws-amplify/ui-components library. Here's a step-by-step solution to replace your console.log(error) with a proper toast notification:
Step 1: Add the Amplify Toast component to your template
First, make sure the <amplify-toast> component is present in your Vue template and assign it a ref so we can access its methods programmatically:
<template> <!-- Your existing component markup --> <amplify-toast ref="authToast" /> </template>
Step 2: Register the component (if not already done)
If you haven't globally registered the Amplify components, import and declare the AmplifyToast in your component's script section:
import { AmplifyToast } from '@aws-amplify/ui-components' export default { components: { AmplifyToast }, // Your existing data, store, watchers, etc. }
Step 3: Update the watch handler to trigger the toast
Replace the console.log(error) line in your catch block with a call to the toast's show method. We'll handle different error scenarios to show meaningful messages:
watch: { authState: { async handler(state) { const data = this.authData if (state === 'signedin') { try { const local = await this.axios.post('/api/v1/authentication/login', { token: data.getSignInUserSession().getIdToken().getJwtToken() }) if ( ! local.data.error) { await this.$store.dispatch('login', data) } } catch (error) { // Trigger error toast notification this.$refs.authToast.show({ // Use backend error message if available, fall back to generic message message: error.response?.data?.message || error.message || 'Failed to complete login', type: 'error', // Sets the toast style to error (red) duration: 5000 // Toast stays visible for 5 seconds (adjust as needed) }) } } }, immediate: true } },
Key Notes:
- Ref Access: The
ref="authToast"lets us access the component instance viathis.$refs.authToast– make sure the ref name matches exactly what you used in the template. - Error Message Handling: The optional chaining (
?.) ensures we don't throw errors iferror.responseorerror.response.datadoesn't exist (like in network errors). We provide fallback messages so users always see something meaningful. - Toast Configuration: The
typeparameter controls the toast's styling (options areerror,success,info). Thedurationis in milliseconds – omit it if you want to use the library's default timeout.
内容的提问来源于stack exchange,提问作者zoltalar

