Vue not updating on property change - vue.js

I've got an index component that contains this, in part:
<template>
<ul class="nav navbar-nav navbar-right">
<li v-if="state.user"><a #click.stop="do_logout" v-link="{ path: '/'}">Logout {{ state.user.display_name }}</a></li>
<li v-else v-link-active><a v-link="{ path: '/login' }">Login</a></li>
</ul>
<router-view></router-view>
<template>
<script>
import state from '../state';
import { logout } from '../actions';
export default {
data() {
return {
state
};
},
methods: {
do_logout() {
logout().then(() => this.$router.go('/'));
}
}
}
</script>
And I've got a login component that looks like this:
<template>
<form class="form-signin" #submit.prevent="do_login">
<input type="email" v-model="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<input type="password" v-model="password" id="inputPassword" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign In</button>
</form>
</template>
<script>
import { login } from '../../actions';
export default {
data() {
return {
email: '',
password: ''
};
},
methods: {
do_login() {
login(this.email, this.password).then(() => this.$router.go('/'));
}
}
}
</script>
My login and logout methods look like this:
import state from './state';
export const login = (email, pwd) => {
return fetch_post_json('/api/login', {
email,
pwd
}).then(j => state.user = j.user);
};
export const logout = () => _fetch('/api/logout', 'GET', null, false).then(() => state.user = null);
Logging out works fine; clicking the link changes the text and presents the "Login" link. Logging in succeeds in logging in, in the Javascript, but doesn't update the link. I'm forced to reload the page to get the page to render correctly. Why?

Related

Submit form free when from errors in VueJs

I'm currently building a form in Vue and I'm having a hard time submitting the form when the form is free from error messages.
I'm currently fixed so that the errors show when they should but the goal is to change the page after pressing the submit button.
I would appreciate any tip that could help me :)
HTML
<template>
<form #submit.prevent="submitMessage">
<div class="form-control">
<label for="user-name">Name*</label>
<input id="user-name" name="user-name" type="text" v-model="userName" />
</div>
<div class="form-control">
<label for="age">Age</label>
<input id="age" name="age" type="number" v-model="userAge" />
</div>
<div class="form-control">
<label for="email">Email*</label>
<input id="email" name="email" type="email" v-model="email" />
</div>
<div class="form-control">
<label for="referrer">How did you hear about us?</label>
<select id="referrer" name="referrer" v-model="referrer">
<option value="google">Google</option>
<option value="wom">Word of mouth</option>
<option value="newspaper">Social Media</option>
<option value="other">Other</option>
</select>
</div>
<div class="form-control">
<label for="message">Message*</label>
<textarea rows="5" cols="50" id="message" name="message" v-model="message">Aa</textarea>
</div>
<div>
<button id="send" #click="sendForm()">Send Message</button>
</div>
<div class="errors">
<p v-if="errors.length > 0">
<b>Please correct the following error(s):</b>
<ul>
<li v-for="error in errors">{{ error }}</li>
</ul>
</p>
</div>
</form>
</template>
Vue
<script>
export default {
data() {
return {
userName: '',
userAge: null,
referrer: 'google',
email: '',
message: '',
errors: []
};
},
methods: {
submitMessage(e) {
this.userName = '';
this.userAge = null;
this.email = '';
this.referrer = 'google';
this.message = ''
},
sendForm() {
this.errors = [];
if (!this.userName) {
this.errors.push('Name is required');
}
if (!this.email) {
this.errors.push('Email is required');
} else if (!this.validEmail(this.email)) {
this.errors.push('Valid email required.');
}
if (!this.message) {
this.errors.push('Message is required');
}
if (!this.errors.length) {
return true;
}
if (this.errors.any()) {
this.$router.push('/thankyou');
}
},
validEmail: function (email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
}
}
</script>
Router.js
import {
createRouter,
createWebHistory
} from 'vue-router';
import HomeBeerSearch from './pages/beers/HomeBeerSearch.vue';
import BeerList from './pages/beers/BeerList.vue';
import CustomerSupport from './pages/contact/CustomerSupport.vue';
import ThankYou from './pages/contact/ThankYou.vue'
const router = createRouter({
history: createWebHistory(),
routes: [{
path: '/',
component: HomeBeerSearch
},
{
path: '/beers',
component: BeerList
},
{
path: '/support',
component: CustomerSupport
},
{
path: '/thankyou',
component: ThankYou
}
]
});
export default router
You can change the page by Vue router on SPA:
this.$router.push({ name: 'route name' })
or you can use raw JavaScript for external links:
window.location.href = 'http://www.google.com';
// there is no such function errors.any()
if (this.errors.any()) {
this.$router.push('/thankyou');
}
Your doing the navigation correctly but I think that the if statment logic is a little flawed. Try this instead:
// check if there are errors; if not go to the thank you page
if (!this.errors.length) {
this.$router.push('/thankyou');
}

VueJs Internal Server Error 500 when direct access url

I have created one login page using VuejS and when I'm accessing directly into the browser in server it gives me 500 error. but when i click from my website it works.
My Login.vue :
<template>
<div>
<div v-if="progress" class="progress-bg">
<div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>
</div>
<section class="container login">
<h1 class="login-title text-center">Login With Email</h1>
<form>
<p v-if="error">{{error}}</p>
<div class="form-group">
<input type="text" v-on:keyup="validate()" v-model="email" :disabled="disabled" class="edt-text" name="email" placeholder="Email">
<p v-if="emailError">{{ emailError}}</p>
</div>
<div class="form-group">
<input type="password" v-on:keyup="validate()" v-model="password" :disabled="disabled" class="edt-text" name="password" placeholder="Password">
<p v-if="passwordError">{{ passwordError}}</p>
</div>
<p class="label-forgot-password">Forgot Password?</p>
<div class="form-group">
<button type="button" :disabled="disabled" v-on:click="login" class="btn-login">Login</button>
</div>
</form>
<p class="text-center">Or Connect With</p>
<div class="row social-login-buttons text-center">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<button type="button" class="btn-google"><i class="fa fa-google"></i>Google</button>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<button type="button" class="btn-facebook"><i class="fa fa-facebook"></i>Facebook</button>
</div>
</div>
<div class="row">
<p class="text-center yellow-text margin-20">Don't you have an account?</p>
</div>
</section>
</div>
</template>
<script>
import axios from 'axios'
export default {
name:"Login",
data() {
return {
email:'',
password:'',
progress:false,
disabled:false,
emailError:null,
passwordError:null,
error:null,
}
},
methods: {
async login() {
this.error = ''
if (this.email && this.password && this.validEmail(this.email)) {
this.progress = true
this.disabled = true
let result = await axios.get(
`https://example.com/login/direct?email=${this.email}&password=${this.password}`
)
this.progress=false
this.disabled=false
if(result.status == "200"){
if(result.data['status'] == true) {
localStorage.setItem("user-token", JSON.stringify(result.data['token']))
this.$router.push({name:'Home'})
}
else {
this.error = "Invalid email address / password"
this.email=''
this.password=''
}
}
}
else {
this.validate()
}
},
validate() {
if (!this.email) {
this.emailError = 'Email address required.';
}
else if (!this.validEmail(this.email)) {
this.emailError = 'Enter valid email address.';
}
else{
this.emailError = null;
}
if (!this.password) {
this.passwordError = 'Password is required';
}
else{
this.passwordError = null;
}
},
validEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
},
}
};
</script>
My router/index.js :
import Vue from 'vue'
import VueRouter from 'vue-router'';
import ChatList from '../views/Chat/ChatList.vue'
import Chat from '../views/Chat/Chat.vue'
import Login from '../views/Login/Login.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/inbox',
name: 'ChatList',
component:ChatList
},
{
path: '/chat',
name: 'Chat',
component:Chat
},
{
path: '/login',
name: 'Login',
component:Login
},
]
const router = new VueRouter({
mode:'history',
routes
})
export default router
I'm able to access my login page when i click from my site which is linked via hyper link but when i directly hit the url into browser address bar it gives me Internal server error.

Vue JS: Forms are not getting cleared when router.push() method is executed after the logout

I am using Flask as a backend and Vue JS as front end for my development. Vuex for state store.
In the logout() I am clearing the authentication token from localStorage via store.dispatch('/logout') and then using router.push('/login') to navigate to Login.vue. I find that the form details entered before are not getting cleared. When the logout() is performed it navigates to the Login.vue with flash message stating 'You have been logged out successfully'.
Below is the code snippet for the same:
logout() {
axios.get(`${this.host}:5000/logout`)
.then((res) => {
this.$store.dispatch('logout')
.then(() => {
this.$router.push('/login');
});
this.flashMessage.success({
message: res.data.msg,
time: 5000,
flashMessageStyle: {
backgroundColor: 'linear-gradient(#e66465, #9198e5)',
},
});
})
.catch((error) => {
this.flashMessage.error({
message: error.toString(),
time: 5000,
flashMessageStyle: {
backgroundColor: 'linear-gradient(#e66465, #9198e5)',
},
});
});
}
logout() is written in App.vue. Here router is an instance of vue-router.
To avoid the issue of form data not being cleared I have used router.go() instead of router.push() in the above code. But because of this implementation, the flash message is not getting displayed as the reload (because of router.go()) is overwriting the displaying of flash message which I don't want.
Please let me if it is possible to erase the form data after logout without getting into the trouble of not showing flash message.
Not sure how you have implemented Login.vue, but here is a Login.vue that I have implemented, and it works. One of the takeaways should be that my form model data values are initialized to empty strings.
<template>
<div id="login">
<form class="form-horizontal">
<div class="form-group">
<label for="username" class="col-md-offset-3 col-md-2 align-right">User Name</label>
<div class="col-md-3">
<input type="input" ref="username" class="form-control" id="username" v-model="username">
</div>
</div>
<div class="form-group">
<label for="password" class="col-md-offset-3 col-md-2 align-right">Password</label>
<div class="col-md-3">
<input type="password" class="form-control" id="password" v-model="password" v-on:keyup.enter="login">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5 col-md-4">
<button type="button" class="btn btn-default"
v-on:click="login">Login</button>
<span class="error-msg" v-if="errorMsg">{{ errorMsg }}</span>
</div>
</div>
</form>
</div>
</template>
<script>
import { loginUrl, axios, processAjaxLoginError } from '../globalvars.js'
export default {
name: 'Login',
data() {
return {
username: '',
password: '',
errorMsg: ''
}
},
methods: {
login() {
axios.post(loginUrl, {
username: this.username,
password: this.password
})
.then(response => {
// Commit the token to the store
this.$store.commit('updateToken', { token: response.data.message });
// Clear error message
this.errorMsg = '';
// Redirect to customer index view
this.$router.push("/customers")
})
.catch(error => {
this.errorMsg = processAjaxLoginError(error);
})
}
},
computed: {
token() {
return this.$store.state.token;
}
},
mounted() {
this.$refs.username.focus();
}
}
</script>

Vuex state inserts [object Object] into input when binded

The issue is that when I bind :value to an input to Vuex and say #input for a method, Vuex causes the input to automatically become an object. When I state it should be the data of the input object via += that doesn't account for deletes and gets messy.
I'm using a module in my Vuex. Below, first, is my template for registration.
<template>
<div class="register-container container">
<div class="auth-form">
<div class="form container">
<div class="title">Sign up to Site</div>
<div class="form">
<div class="input el-input">
<input type="text" placeholder="Email" :value="registrationEmail" #input="setRegistrationEmail" class="el-input__inner">
</div>
<div class="input el-input">
<input type="text" placeholder="Username" :value="registrationUsername" #input="setRegistrationUsername" class="el-input__inner">
</div>
<div class="input el-input">
<input type="password" placeholder="Password" :value="registrationPassword" #input="setRegistrationPassword" class="el-input__inner">
</div>
<div class="input el-input">
<input type="password" placeholder="Confirm Password" v-model="confirm_password" class="el-input__inner">
</div>
<div class="submit btn-pill"><span class="content" #click="register">Sign Up</span></div>
</div>
Have an account? <span class="blue">Log in!</span>
</div>
</div>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
export default {
data() {
return {
confirm_password: '',
};
},
methods: {
...mapMutations('authentication', [
'setRegistrationEmail',
'setRegistrationPassword',
'setRegistrationUsername',
]),
...mapActions('authentication', [
'register',
]),
},
computed: {
...mapState('authentication', [
'registrationEmail',
'registrationPassword',
'registrationUsername',
]),
},
};
</script>
Here is the mdoule:
import HTTP from '../http';
export default {
namespaced: true,
state: {
registrationEmail: null,
registrationPassword: null,
registrationUsername: null,
},
actions: {
register({ state }) {
return HTTP().post('/api/auth/register', {
email: state.registrationEmail,
username: state.registrationUsername,
password: state.registrationPassword,
});
},
},
mutations: {
setRegistrationEmail(state, email) {
console.log(email);
state.registrationEmail = email;
},
setRegistrationPassword(state, password) {
state.registrationPassword = password;
},
setRegistrationUsername(state, username) {
state.registrationUsername = username;
},
},
};
You need to do something like this, link
Call the setRegistrationEmail from a method instead of directly calling it.
<input type="text" :value="registrationEmail" #change="setEmail" class="el-input__inner">
and inside methods
methods: {
setEmail(e) {
this.setRegistrationEmail(e.target.value)
},
...mapMutations('authentication', [
'setRegistrationEmail',
'setRegistrationPassword',
'setRegistrationUsername',
]),
...mapActions('authentication', [
'register',
]),
},

I got Vue errors rendering component

I have a "vue-cli webpack" like the following :
src/components/Signin.vue:
<template>
...
<form v-on:submit.prevent="userSignIn">
...
<div class="field">
<p class="control has-icons-left has-icons-right">
<input
v-validate="'required|email'"
v-bind:class="{'is-danger': errors.has('name')}"
name="email"
v-model="form.email"
class="input"
id="email"
type="email"
placeholder="Email"
>
<span class="icon is-small is-left">
<i class="fa fa-envelope"></i>
</span>
<span class="icon is-small is-right">
<i class="fa fa-check"></i>
</span>
<span class="help is-danger" v-show="errors.has('email')">{{ errors.first('email') }}</span>
</p>
</div>
<div class="field">
<p class="control has-icons-left">
<input
v-validate="'required|min:5'"
v-bind:class="{'is-danger': errors.has('name')}"
name="password"
v-model="form.password"
class="input"
id="password"
type="password"
placeholder="Password"
>
<span class="icon is-small is-left">
<i class="fa fa-lock"></i>
</span>
<span class="help is-danger" v-show="errors.has('password')">{{ errors.first('password') }}</span>
</p>
</div>
<div class="field is-grouped">
<div class="control">
<button v-bind:disabled="errors.any()" class="button is-primary" type="submit" :disabled="loading">
Submit
</button>
</div>
</div>
</form>
...
</template>
<script>
...
export default {
data () {
return {
form: {
email: '',
password: '',
alert: false
}
}
},
computed: {
error () {
return this.$store.getters.getError
},
loading () {
return this.$store.getters.getLoading
}
},
watch: {
error (value) {
if (value) {
this.alert = true
}
},
alert (value) {
if (!value) {
this.$store.dispatch('setError', false)
}
},
methods: {
userSignIn () {
this.$store.dispatch('userSignIn', {email: this.email, password: this.password})
}
}
},
...
}
</script>
src/App.vue:
<template>
<main>
<router-view></router-view>
</main>
</template>
<style lang="sass">
#import "~bulma"
/* Your css for this file... */
</style>
src/main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import firebase from 'firebase'
import { store } from './store'
import VeeValidate from 'vee-validate'
import { firebaseConfig } from './config'
Vue.use(VeeValidate)
Vue.config.productionTip = false
firebase.initializeApp(firebaseConfig)
/* eslint-disable no-new */
const unsubscribe = firebase.auth()
.onAuthStateChanged((firebaseUser) => {
new Vue({
el: '#app',
router,
store,
render: h => h(App),
created () {
store.dispatch('autoSignIn', firebaseUser)
}
})
unsubscribe()
})
and I get two errors when I click the button :
Property or method "userSignIn" is not defined on the instance but
referenced during render. Make sure to declare reactive data
properties in the data option.
Signin.vue?d58e:24 Uncaught TypeError: _vm.userSignIn is not a
function
You've defined your methods inside your watch. Move them outside.
watch: {
error (value) {
if (value) {
this.alert = true
}
},
alert (value) {
if (!value) {
this.$store.dispatch('setError', false)
}
},
},
methods: {
userSignIn () {
this.$store.dispatch('userSignIn', {email: this.email, password: this.password})
}
}