Skip to content

Instantly share code, notes, and snippets.

@phazonoverload

phazonoverload/App.vue Secret

Created Jan 2, 2020
Embed
What would you like to do?
Blog: Persisting data between app launches with NativeScript Vue
<template lang="html">
<Page @loaded="checkToken">
<ActionBar title="App" />
<StackLayout>
<Button text="Login" @tap="logout" />
</StackLayout>
</Page>
</template>
<script>
export default {
methods: {
logout() {
this.$store.dispatch('clearUser')
}
}
}
<script>
<template lang="html">
<Page @loaded="checkToken">
<ActionBar title="Login" />
<StackLayout>
<TextField v-model="email" hint="Email Address" />
<TextField v-model="password" hint="Password" secure="true" />
<Button text="Login" @tap="login" />
</StackLayout>
</Page>
</template>
<script>
import axios from 'axios';
export default {
methods: {
checkToken() {
this.$store.commit("loadFromStorage");
if(state.token) {
this.$navigateTo(App, {
clearHistory: true
})
}
}
}
async login() {
axios.post('LOGIN API URL', {
email: this.email,
password: this.password
}).then(data => {
this.$store.dispatch('setUser', data).then(() => {
this.$navigateTo(App, {
clearHistory: true
})
})
})
}
},
data() {
return {
email: '',
password: ''
}
}
}
</script>
import * as ApplicationSettings from "application-settings";
import Vue from 'nativescript-vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state = {
token: false
}
const mutations = {
loadFromStorage(state) {
const storedState = ApplicationSettings.getString("token");
if(storedState) {
const token = JSON.parse(storedState);
state.token = token;
}
},
setUser(state, token) {
state.token = token;
ApplicationSettings.setString("token", JSON.stringify(token));
},
clearUser(state) {
state.token = false;
ApplicationSettings.remove("token");
}
}
const actions = {
setUser({ commit }, token) {
commit('setUser', token);
},
clearUser({ commit }) {
commit('clearUser');
}
}
const getters = {}
export default new Vuex.Store({state, mutations, actions, getters});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment