Why style.backgroundImage returns empty? - javascript

So here is the HTML
<button class="w drum">w</button>
<script src="index.js" charset="utf-8"></script>
And This is the CSS
.w {
background-image: url("images/tom1.png");
}
.a {
background-image: url("images/tom2.png");
}
.s {
background-image: url("images/tom3.png");
}
.d {
background-image: url("images/tom4.png");
}
.j {
background-image: url("images/snare.png");
}
.k {
background-image: url("images/crash.png");
}
.l {
background-image: url("images/kick.png");
}
Lastly this is the javascript
for (let i in document.querySelectorAll(".drum")) {
document.querySelectorAll(".drum")[i].addEventListener("click", handleClick);
}
function handleClick() {
var url = this.style.backgroundImage;
console.log(url);
}
So when I click on w / a / s / d / etc. button, Console should return the image url right?
But this is what happened...
Console log shows empty string
Why is it empty??? Plz help

Use NodeList.prototype.forEach() and Window.getComputedStyle
const handleClick = (evt) => {
const url = getComputedStyle(evt.currentTarget).backgroundImage;
console.log(url);
}
document.querySelectorAll(".drum").forEach((elDrum) => {
elDrum.addEventListener("click", handleClick);
});

import { createApp, markRaw } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import vue3GoogleLogin from 'vue3-google-login'
import './assets/style.css'
const app = createApp(App)
app.use(vue3GoogleLogin, {
clientId: '433430770978-3pff7bk6ff4qmcc8qnvpckqil6q17bg2.apps.googleusercontent.com'
})
const pinia = createPinia()
pinia.use(({ store }) => {
store.router = markRaw(router)
})
app.use(router)
app.use(pinia)
app.mount('#app')
di dalam router:
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{path: '/', name: 'home', component: Home},
{path: '/menu', name: 'menu', component: Menu},
{path: '/login', name: 'login', component: Login, beforeEnter:(to, from, next) => {
if(!localStorage.getItem("access_token")) {
next()
} else{
next('/')
}
}},
{path: '/register', name: 'register', component: Register, beforeEnter:(to, from, next ) => {
if(!localStorage.getItem("access_token")) {
next()
} else{
next('/')
}
}},
{path: '/menu/:id', name: 'detail', component: Detail},
{path: '/favorite', name: 'favorite', component: Favorite, beforeEnter:(to, from, next) => {
if(localStorage.getItem("access_token")){
next()
} else{
next('/')
}
}},
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
di dalam store nya
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios';
export const useAppStore = defineStore("app", {
state: () => ({
isAuth: false,
foods: [],
food: {},
favorite: [],
}),
getters:{},
actions:{
checkAuth(){
this.isAuth = !!localStorage.getItem('access_token')
},
// tempat methode terjadi
}
})
di dalam component:
import {mapActions, mapState, mapWritableState } from "pinia"
import { useAppStore } from './stores/app'
export default{
name: "Register",
components:{},
data(){
return{
data:{
email: "",
password: "",
phoneNumber: "",
address: "",
}
}
},
computed:{
...mapState(useAppStore,["var"])
},
methods:{
...mapActions(useAppStore, ["var"])
},
created(){
}
}

Related

"TypeError: next is not a function" in the router.js file of my vue 3 project when trying to apply navigation guards?

I don't understand why i doesn't recognise the next function whereas i followed a similar video implementing this and it worked with no errors
I don't understand why i doesn't recognise the next function whereas i followed a similar video implementing this and it worked with no errors
I don't understand why i doesn't recognise the next function whereas i followed a similar video implementing this and it worked with no errors
import Dashboard from "./Pages/Dashboard.vue";
import Customers from "./Pages/Customers.vue";
import EditProfile from "./Pages/EditProfile.vue";
import Insurance from "./Pages/Insurance.vue";
import Activations from "./Pages/Activations.vue";
import Login from "./Pages/Login.vue"
import ForgotPassword from "./Pages/ForgotPassword.vue"
import MyDashboard from "./Pages_cus/MyDashboard.vue";
import MyActivations from "./Pages_cus/MyActivations.vue";
import MyEditProfile from './Pages_cus/MyEditProfile.vue';
import NotFound from './Pages/NotFound.vue';
import NetworkError from './Pages/NetworkError.vue'
import { createRouter, createWebHistory } from "vue-router";
const routes = [
{
name: "MyDashboard",
component: MyDashboard,
path: "/my-dashboard",
meta: {
requiresAuth: true,
}
},
{
name: "MyActivations",
component: MyActivations,
path: "/my-activations",
},
{
name: "MyEditProfile",
component: MyEditProfile,
path: "/my-edit-profile",
},
{
name: "Dashboard",
component: Dashboard,
path: "/dashboard",
meta: {
requiresAuth: true,
}
},
{
name: "Customers",
component: Customers,
path: "/customers",
},
{
name: "EditProfile",
component: EditProfile,
path: "/edit-profile",
},
{
name: "Insurance",
component: Insurance,
path: "/insurance",
},
{
name: "Activations",
component: Activations,
path: "/activations",
},
{
name: "Login",
component: Login,
path: "/",
meta: {
requiresAuth: true,
}
},
{
name: "ForgotPassword",
component: ForgotPassword,
path: "/forgot-password",
},
{
name: "404Resource",
component: NotFound,
path: '/404/:resource',
props:true
},
{
name: "NetworkError",
component: NetworkError,
path: '/network-error'
},
{
name: "NotFound",
component: NotFound,
path: '/:catchAll(.*)'
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
router.beforeEach((to, next)=>{
if (to.matched.some(record => record.meta.requiresAuth)) {
if (localStorage.getItem('token') == null) {
console.log('Hello JS')
next({
path: '/',
params: { nextUrl: to.fullPath }
}) // I get the error at this level it doesn't recognise next as a function
}
else{
next();
}
}
else {
next()
}
})
export default router;
[Screenshot of code in VS code][1]
[Screenshot of code in browser
<!-- begin snippet: js hide: false console: true babel: false -->
import Dashboard from "./Pages/Dashboard.vue";
import Customers from "./Pages/Customers.vue";
import EditProfile from "./Pages/EditProfile.vue";
import Insurance from "./Pages/Insurance.vue";
import Activations from "./Pages/Activations.vue";
import Login from "./Pages/Login.vue"
import ForgotPassword from "./Pages/ForgotPassword.vue"
import MyDashboard from "./Pages_cus/MyDashboard.vue";
import MyActivations from "./Pages_cus/MyActivations.vue";
import MyEditProfile from './Pages_cus/MyEditProfile.vue';
import NotFound from './Pages/NotFound.vue';
import NetworkError from './Pages/NetworkError.vue'
import { createRouter, createWebHistory } from "vue-router";
const routes = [
{
name: "MyDashboard",
component: MyDashboard,
path: "/my-dashboard",
meta: {
requiresAuth: true,
}
},
{
name: "MyActivations",
component: MyActivations,
path: "/my-activations",
},
{
name: "MyEditProfile",
component: MyEditProfile,
path: "/my-edit-profile",
},
{
name: "Dashboard",
component: Dashboard,
path: "/dashboard",
meta: {
requiresAuth: true,
}
},
{
name: "Customers",
component: Customers,
path: "/customers",
},
{
name: "EditProfile",
component: EditProfile,
path: "/edit-profile",
},
{
name: "Insurance",
component: Insurance,
path: "/insurance",
},
{
name: "Activations",
component: Activations,
path: "/activations",
},
{
name: "Login",
component: Login,
path: "/",
meta: {
requiresAuth: true,
}
},
{
name: "ForgotPassword",
component: ForgotPassword,
path: "/forgot-password",
},
{
name: "404Resource",
component: NotFound,
path: '/404/:resource',
props:true
},
{
name: "NetworkError",
component: NetworkError,
path: '/network-error'
},
{
name: "NotFound",
component: NotFound,
path: '/:catchAll(.*)'
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
router.beforeEach((to, next)=>{
if (to.matched.some(record => record.meta.requiresAuth)) {
if (localStorage.getItem('token') == null) {
console.log('Hello JS')
next({
path: '/',
params: { nextUrl: to.fullPath }
}) // I get the error at this level it doesn't recognise next as a function
}
else{
next();
}
}
else {
next()
}
})
export default router;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
[1]: https://i.stack.imgur.com/Y9D08.png
[2]: https://i.stack.imgur.com/n9ERj.png
next is the third argument for the beforeEach function, so it should be:
beforeEach((to, from, next)) => {...
While you're using the next function correctly here (ensuring that it's called exactly once), it is currently deprecated: https://github.com/vuejs/rfcs/blob/master/active-rfcs/0037-router-return-guards.md#motivation
It's now suggested to use 1 or 2 arguments and return a boolean value to indicate whether or not to proceed, or a route to redirect to:
router.beforeEach((to)=>{
if (to.matched.some(record => record.meta.requiresAuth)
&& localStorage.getItem('token') == null) {
//redirect
return {
name: '/',
query: { nextUrl: to.fullPath }
}
}
return true; //proceed (equivalent of next())
});

Why is router.push not working? [Vue3] [Vuex4]

I have some issues with Vue 3 and Vuex.
I'm trying to redirect users when logged in in my Vuex file, but it's not working as expected.
It's not returning any errors, it's changing a link, but not redirected to another page.
My action looks like this;
actions: {
async login(commit: any, payload: any ) {
const cookie_token = useCookies();
API.post('/login', {
email: payload.email.value,
password: payload.password.value
})
.then((response: any) => {
notif.success('Welcome back, ' + response.data.player.name)
cookie.set('user', response.data)
commit.commit('loginSuccess', response.data)
router.push({
name: 'index',
})
}).catch((e) => (
console.log(e.message)
)
)
}
},
And the router is getting files where routes are defined.
And here is my full router file:
import {
createRouter as createClientRouter,
createWebHistory,
} from 'vue-router'
import * as NProgress from 'nprogress'
// import routes from 'pages-generated'
import type { RouteRecordRaw } from "vue-router";
// Then we can define our routes
const routes: RouteRecordRaw[] = [
// This is a simple route
{
component: () => import("/#src/pages/index.vue"),
name: "index",
path: "/",
props: true,
},
{
component: () => import("/#src/pages/auth.vue"),
path: "/auth",
props: true,
children: [
{
component: () => import("/#src/pages/auth/login.vue"),
name: "auth-login",
path: "login-1",
props: true,
},
{
component: () => import("/#src/pages/auth/login.vue"),
name: "auth-signup",
path: "singup",
props: true,
},
],
},
{
component: () => import("/#src/pages/[...all].vue"),
name: "404",
path: "/:all(.*)",
props: true,
},
];
export function createRouter() {
const router = createClientRouter({
history: createWebHistory(),
routes,
})
/**
* Handle NProgress display on-page changes
*/
router.beforeEach(() => {
NProgress.start()
})
router.afterEach(() => {
NProgress.done()
})
return router
}
export default createRouter()
Have in mind that it's working on other files, and I can see that router is triggered here, but not chaning a page, only on vuex is not working. If it's not working, why there is no error?
You're creating more than one instance of Vue Router. You should export the same router instance, not a function creating a new instance each time it gets called.
The following code will likely yield the desired outcome:
import {
createRouter,
createWebHistory,
} from 'vue-router'
import * as NProgress from 'nprogress'
import type { RouteRecordRaw } from "vue-router";
const routes: RouteRecordRaw[] = [
// your routes here...
];
let router;
export function useRouter() {
if (!router) {
router = createRouter({
history: createWebHistory(),
routes,
})
router.beforeEach(() => {
NProgress.start()
})
router.afterEach(() => {
NProgress.done()
})
}
return router
}
I'm placing the router instance in the outer scope, so you always get the same instance when calling useRouter().
Consume it using:
import { useRouter } from '../path/to/router'
const router = useRouter();

Readonly issue when using vuex-persistedstate

I'm getting an error that has me stumped. I want to keep the open/close state of the q-drawer component in the Vuex store and keep it open/closed after the page is refreshed. The components work as expected until I add the vue-persistedstate plugin to the store. The console says [Vue warn]: Write operation failed: computed property "drawerOpen" is readonly. I never set anything to readonly on purpose so I cannot find which line of code caused the issue. Other data of the store do not have an issue.
I will post the excerpts of code that are potentially relevant. There are no references to drawerOpen elsewhere in the code.
MainLayout.vue
<q-drawer
v-model="drawerOpen"
show-if-above
bordered
class="bg-grey-1"
>
<q-list>
<q-item-label
header
class="text-grey-8"
>
Essential Links
</q-item-label>
<EssentialLink
v-for="link in essentialLinks"
:key="link.title"
v-bind="link"
/>
</q-list>
</q-drawer>
<q-page-container>
<router-view />
</q-page-container>
</q-layout>
</template>
<script>
import EssentialLink from 'components/EssentialLink.vue'
import { computed, defineComponent, ref } from 'vue'
import { useStore } from 'vuex'
const linksList = [
{
title: 'Dashboard',
caption: 'See your progress',
icon: 'dashboard',
link: ''
},
{
title: 'Courses',
caption: 'Learn something new',
icon: 'school',
link: 'https://github.com/quasarframework'
},
{
title: 'Forum',
caption: 'Find like-minded people',
icon: 'chat',
link: 'https://chat.quasar.dev'
},
{
title: 'Support',
caption: 'We\'re here to help',
icon: 'record_voice_over',
link: 'https://chat.quasar.dev'
},
];
import { mapGetters, mapActions } from 'vuex'
export default {
name: 'MainLayout',
components: {
EssentialLink
},
computed: {
...mapGetters({
username: 'profile/getUsername',
drawerOpen: 'profile/getDrawerOpen',
}),
},
methods: {
...mapActions({
close_open_drawer: 'profile/toggleDrawer'
}),
},
setup () {
return {
essentialLinks: linksList
}
}
}
</script>
state.js
export default function () {
return {
drawerOpen: true,
email: '',
username: '',
userToken: '',
test: ''
}
}
actions.js
...
export const toggleDrawer = (state, payload) => {
state.commit("toggleDrawer", payload)
}
mutations.js
...
export const toggleDrawer = (state, payload) => {
state.drawerOpen = !state.drawerOpen
}
index.js
import { store } from 'quasar/wrappers'
import { createStore } from 'vuex'
import createPersistedState from "vuex-persistedstate";
import profile from './profile'
export default store(function (/* { ssrContext } */) {
const Store = createStore({
modules: {
profile
},
plugins: [createPersistedState()],
strict: process.env.DEBUGGING
})
return Store
})

Angular: E2E Test via login page

I have an Angular application using an Express.js backend. It features a default address pathway to a login page /avior/login. I need to write an E2E Test for the whole application and I just started writing the first test part which is supposed to recognize the login page and login itself and then check whether the redirect was successful. I have wrote this error-prone code so far:
import { AppPage } from './app.po';
import { browser, logging, element } from 'protractor';
import { async, ComponentFixture, fakeAsync, TestBed, tick,
} from '#angular/core/testing';
import {AppComponent} from '../../src/app/app.component'
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let page: AppPage;
let router: Router;
let location: SpyLocation;
let username: 'Test';
let password: 'testtest';
let usernameInput: element(by.css('#inputUser'));
let passwordInput: element(by.css('#inputPassword'));
let loginButton: element(by.css('#loginSubmit'));
describe('Avior App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should navigate to "/avior/login" immediately', fakeAsync(() => {
createComponent();
tick(); // wait for async data to arrive
expect(location.path()).toEqual('/avior/login', 'after initialNavigation()');
expectElementOf(DashboardComponent);
}));
it('should display Login message in the header', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('Anmeldung');
});
it('there should be username and password login fields', () => {
// how to check?
});
it('login using false credentials should make you stay put and throw an error', () => {
// how to?
});
it('login using Test:testtset (=successful credentials => successful login) should redirect to /avior/dashboard', () => {
// how to?
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});
function createComponent() {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
const injector = fixture.debugElement.injector;
location = injector.get(Location) as SpyLocation;
router = injector.get(Router);
router.initialNavigation();
spyOn(injector.get(TwainService), 'getQuote')
// fake fast async observable
.and.returnValue(asyncData('Test Quote'));
advance();
page = new Page();
}
function loginFn() {
usernameInput.sendKeys(username);
passwordInput.sendKeys(password);
loginButton.click();
};
How to fix this code?
UPDATE
I tried simplifying my code to only include routing tests so far and I get new errors thrown out.
My new code is the following:
import { AppPage } from './app.po';
import { browser, logging, element } from 'protractor';
import { async, ComponentFixture, fakeAsync, TestBed, tick,
} from '#angular/core/testing';
import {AppComponent} from '../../src/app/app.component'
import {Component} from "#angular/core";
import {RouterTestingModule} from "#angular/router/testing";
import {Routes} from "#angular/router";
import {Router} from "#angular/router";
import { AviorComponent } from '../../src/app/avior/avior.component';
import { DashboardComponent } from '../../src/app/avior/dashboard/dashboard.component';
import { ProfileComponent } from '../../src/app/avior/profile/profile.component';
import { SettingsComponent } from '../../src/app/avior/settings/settings.component';
import { LoginComponent } from '../../src/app/avior/login/login.component';
import { PageNotFoundComponent } from '../../src/app/avior/page-not-found/page-not-found.component';
import { InfoComponent } from '../../src/app/avior/info/info.component';
import { UsersComponent } from '../../src/app/avior/users/users.component';
import { MandatorsComponent } from '../../src/app/avior/mandators/mandators.component';
import { SystemComponent } from '../../src/app/avior/system/system.component';
import { WorkflowsComponent } from '../../src/app/avior/workflows/workflows.component';
import { MessagesComponent } from '../../src/app/avior/messages/messages.component';
import { BrowserDynamicTestingModule,
platformBrowserDynamicTesting } from '#angular/platform-browser-dynamic/testing';
/* let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let page: AppPage;
let router: Router;
let location: SpyLocation;
let username: 'Chad';
let password: 'chadchad';
let usernameInput: element(by.css('#inputUser'));
let passwordInput: element(by.css('#inputPassword'));
let loginButton: element(by.css('#loginSubmit')); */
const aviorRoutes: Routes = [{
path: '', component: AviorComponent,
children: [
{
path: '', component: ProfileComponent
},
{
path: 'dashboard', component: DashboardComponent,
data: {title: 'Dashboard'},
},
{
path: 'login', component: LoginComponent,
data: {title: 'Login'},
},
{
path: 'logout', component: LoginComponent,
data: {title: 'Login'},
},
{
path: 'profile', component: ProfileComponent,
data: {title: 'Profil'},
},
{
path: 'settings', component: SettingsComponent,
data: {title: 'Einstellungen'},
},
{
path: 'info', component: InfoComponent,
data: {title: 'Info'},
},
{
path: 'users', component: UsersComponent,
data: {title: 'Benutzer'},
},
{
path: 'workflows', component: WorkflowsComponent,
data: {title: 'Workflows'},
},
{
path: 'system', component: SystemComponent,
data: {title: 'System'},
},
{
path: 'mandators', component: MandatorsComponent,
data: {title: 'Mandanten'}
},
{
path: 'messages', component: MessagesComponent,
data: {title: 'Nachrichten'}
},
{
path: '404', component: PageNotFoundComponent,
data: {title: 'Page not found'},
}
]
}];
describe('Avior App', () => {
let page: AppPage;
beforeEach(() => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(BrowserDynamicTestingModule,
platformBrowserDynamicTesting())
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes(aviorRoutes)],
declarations: [
DashboardComponent,
ProfileComponent,
SettingsComponent,
LoginComponent,
PageNotFoundComponent,
InfoComponent,
UsersComponent,
MandatorsComponent,
SystemComponent,
WorkflowsComponent,
MessagesComponent
]
});
page = new AppPage();
this.router = TestBed.get(Router);
location = TestBed.get(Location);
this.fixture = TestBed.createComponent(AppComponent);
this.router.initialNavigation();
});
/* it('should navigate to "/avior/login" immediately', fakeAsync(() => {
createComponent();
tick(); // wait for async data to arrive
expect(location.path()).toEqual('/avior/login', 'after initialNavigation()');
expectElementOf(DashboardComponent);
})); */
it('navigate to "" redirects you to /avior/login', fakeAsync(() => {
  this.router.navigate(['']);
tick();
expect(location.path()).toBe('/avior/login');
}));
it('navigate to "dashboard" takes you to /dashboard', fakeAsync(() => {
  this.router.navigate(['dashboard']);
 tick();
expect(location.path()).toBe('avior/dashboard');
}));
it('should display Anmeldung message in the header', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('Anmeldung');
});
it('there should be username and password login fields', () => {
});
it('login using false credentials should make you stay put and throw an error', () => {
});
it('login using Chad:chadchad should redirect to /avior/dashboard', () => {
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});
/* function createComponent() {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
const injector = fixture.debugElement.injector;
location = injector.get(Location) as SpyLocation;
router = injector.get(Router);
router.initialNavigation();
spyOn(injector.get(TwainService), 'getQuote')
// fake fast async observable
.and.returnValue(asyncData('Test Quote'));
advance();
page = new Page();
}
function loginFn(username, password) {
usernameInput.sendKeys(username);
passwordInput.sendKeys(password);
loginButton.click();
};
*/
The errors get thrown out during ng e2e runtime:
- Failed: Can't resolve all parameters for ApplicationModule: (?). - Failed: Cannot read property 'assertPresent' of null

Access Vuex mutators in navigation guards

I'm building an app with Laravel + VueJS. In order to restrict some routes, I use navigation guards. The problem is that I need to access Vuex mutators in order to know if the current user is logged in. The thing is that store is defined, but I cannot use the mutator from the router. I got this error: TypeError: Cannot read property 'commit' of undefined but as I said, store is well defined. Does someone have an idea ? Thanks !
routes
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '#/components/Hello'
import Register from '#/components/Register'
import Login from '#/components/Login'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Hello',
component: Hello,
meta: {
showNavigation: true,
requireAuthentication: true
}
},
{
path: '/register',
component: Register,
meta: {
showNavigation: false,
requireAuthentication: false
}
},
{
path: '/login',
component: Login,
meta: {
showNavigation: false,
requireAuthentication: false
}
}
],
mode: 'history'
})
store
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const store = new Vuex.Store({
state: {
access_token: null,
expires_in: 0
},
mutations: {
setToken (state, response) {
state.access_token = response.body.access_token
state.expires_in = response.body.expires_in + Date.now()
},
getToken (state) {
if (!state.access_token || !state.expires_in) return null
if (state.expires_in < Date.now()) this.commit('destroyToken')
return state.access_token
},
destroyToken (state) {
state.access_token = null
state.expires_in = 0
},
isAuthenticated (state) {
return this.commit('getToken') !== null
}
},
actions: {
getOauthToken (context, user) {
var data = {
client_id: 2,
client_secret: 'XXXXXXXXXXXXXXXXXXXXXXXXXX',
grant_type: 'password',
username: user.email,
password: user.password
}
Vue.http.post('oauth/token', data)
.then(response => {
context.commit('setToken', response)
})
}
}
})
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import { store } from './store'
import VueResource from 'vue-resource'
import VeeValidate from 'vee-validate'
Vue.config.productionTip = false
Vue.use(VueResource)
Vue.use(VeeValidate)
Vue.http.options.root = 'http://codex.app'
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuthentication)) {
console.log(store)
console.log(store.commit('isAuthenticated'))
if (!store.commit('isAuthenticated')) {
next('/login')
} else {
next()
}
} else {
next()
}
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
when we commit mutations, it refers to change the state and ONLY the state.when you need more complex mutations to change the state, using actions instead.

Categories