Now, let's move on to changing user passwords. Within the Settings folder, create a UserPasswordSettings.vue file then paste the code below in it:

// src/components/User/Settings/UserPasswordSettings.vue

<template>
  <div class="ui stackable grid container">
    <UserSettingsMenu/>

    <div class="eight wide column">
      <div class="ui segment">
        <h2 class="ui dividing header">Change Password</h2>

        <Notification
          :message="notification.message"
          :type="notification.type"
          v-if="notification.message"
        />

        <form class="ui form" @submit.prevent="changePassword">
          <div class="field" :class="{ error: errors.has('password') }">
            <label>Current Password</label>
            <input type="password" name="password" v-model="password" data-vv-as="current password" v-validate="'required'">
            <span v-show="errors.has('password')" class="is-danger">{{ errors.first('password') }}</span>
          </div>

          <div class="field" :class="{ error: errors.has('newPassword') }">
            <label>New Password</label>
            <input type="password" name="newPassword" v-model="newPassword" data-vv-as="new password" v-validate="'required'">
            <span v-show="errors.has('newPassword')" class="is-danger">{{ errors.first('newPassword') }}</span>
          </div>

          <div class="field" :class="{ error: errors.has('confirmPassword') }">
            <label>New Password</label>
            <input type="password" name="confirmPassword" v-model="confirmPassword" data-vv-as="confirm password" v-validate="'required|confirmed:newPassword'">
            <span v-show="errors.has('confirmPassword')" class="is-danger">{{ errors.first('confirmPassword') }}</span>
          </div>

          <button type="submit" class="ui button primary" :disabled="!isFormValid">Change password</button>
        </form>
      </div>
    </div>
  </div>
</template>

Again, we are using both the UserSettingsMenu and Notification components. We use the VeeValidate plugin to make sure users enters their current password and also make sure the new password and the confirm password matches. The "Change password" button is disable using a isFormValid computed property until the form is properly filled. Once the form is submitted, a changePassword method is called.

Next, let's add the JavaScript section to the component. Still inside UserPasswordSettings.vue, add the code below just after the template section:

Table of Contents

    // src/components/User/Settings/UserPasswordSettings.vue
    
    <script>
        import Notification from '@/components/Notification'
        import UserSettingsMenu from '@/components/User/Settings/UserSettingsMenu'
    
        export default {
            name: 'UserProfileEditForm',
            components: {
                Notification,
                UserSettingsMenu
            },
            data () {
                return {
                    password: '',
                    newPassword: '',
                    confirmPassword: '',
                    notification: {
                        message: '',
                        type: ''
                    }
                }
            },
            computed: {
                isFormValid () {
                    return Object.keys(this.fields).every(key => this.fields[key].valid)
                },
            },
            beforeRouteEnter (to, from, next) {
                const token = localStorage.getItem('tweetr-token')
    
                return token ? next() : next('/login')
            },
            methods: {
                changePassword () {
                    const token = localStorage.getItem('tweetr-token')
    
                    axios
                        .put(
                            '/account/change_password',
                            {
                                password: this.password,
                                newPassword: this.newPassword
                            },
                            {
                                headers: {
                                    Authorization: `Bearer ${token}`
                                },
                            }
                        )
                        .then(response => {
                            // clear form inputs
                            this.password = this.newPassword = this.confirmPassword = ''
    
                            // display success notification
                            this.notification = Object.assign({}, this.notification, {
                                message: response.data.message,
                                type: 'success'
                            })
                        })
                        .catch(error => {
                            // clear form inputs
                            this.password = this.newPassword = this.confirmPassword = ''
    
                            // clear form error messages
                            this.$nextTick(() => {
                                this.$validator.reset()
                            })
    
                            // display error notification
                            this.notification = Object.assign({}, this.notification, {
                                message: error.response.data.message,
                                type: 'danger'
                            })
                        })
                }
            }
        }
    </script>

    We import both the Notification and UserSettingsMenu components. Then we define our data and the isFormValid computed property. Just as we did in the editing user profile lesson, we make sure only authenticated users can access the form. The changePassword method makes a PUT request to the /account/change_password endpoint of our API, passing along the passwords entered and the user's token. If the password was changed successful, we clear the form input fields and display a success message returned from our API. If there was a problem updating the user password, we first clear the form input fields, and then clear VeeValidate error messages. Finally, we display an appropriate error notification.

    Adding Change Password Route

    Open src/router/index.js, and add the code below to it:

    // src/router/index.js
    
    import UserPasswordSettings from '@/components/User/Settings/UserPasswordSettings'
    
    // add these inside the `routes` array
    {
        path: '/settings/password',
        component: UserPasswordSettings
    },

    Visiting the /settings/password route, we should see the change password form as in the image below:

    Chimezie Enyinnaya

    16 posts

    Software Developer [PHP Laravel JavaScript NodeJS AdonisJS VueJS] | movie lover | run http://openlaravel.com