访问导航警卫中的Vuex变异器

时间:2017-06-27 09:42:57

标签: javascript vue.js vue-router vuex

我正在使用Laravel + VueJS构建应用程序。为了限制一些路线,我使用导航警卫。问题是我需要访问Vuex mutators以了解当前用户是否已登录。问题是store已定义,但我无法使用路由器中的mutator。我收到此错误:TypeError: Cannot read property 'commit' of undefined但正如我所说,store定义明确。有人有想法吗?谢谢!

路由

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'
})

商品

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 }
})

1 个答案:

答案 0 :(得分:2)

当我们提交突变时,它指的是改变状态而只改变状态。当你需要更复杂的突变来改变状态时,改为使用动作。