简体   繁体   English

如何从 javascript 文件(而不是 vue 组件)获取 vuex 状态

[英]How to get vuex state from a javascript file (instead of a vue component)

I am working with vuex (2.1.1) and get things working within vue single file components.我正在使用 vuex (2.1.1) 并在 vue 单文件组件中工作。 However to avoid too much cruft in my vue single file component I moved some functions to a utils.js module which I import into the vue-file.然而,为了避免在我的 vue 单文件组件中出现太多问题,我将一些函数移到了utils.js模块中,然后将其导入到 vue 文件中。 In this utils.js I would like to read the vuex state.在这个utils.js我想阅读 vuex 状态。 How can I do that?我怎样才能做到这一点? As it seems approaching the state with getters etc is presuming you are working from within a vue component, or not?似乎使用 getter 等接近状态是假设您在 vue 组件中工作,或者不是?

I tried to import state from '../store/modules/myvuexmodule' and then refer to state.mystateproperty but it always gives 'undefined', whereas in the vue-devtools I can see the state property does have proper values.我试图import state from '../store/modules/myvuexmodule' ,然后引用state.mystateproperty但它总是给出 'undefined',而在 vue-devtools 中我可以看到 state 属性确实有正确的值。

My estimate at this point is that this is simply not 'the way to go' as the state.property value within the js file will not be reactive and thus will not update or something, but maybe someone can confirm/ prove me wrong.我在这一点上的估计是,这根本不是“要走的路”,因为 js 文件中的 state.property 值不会是反应性的,因此不会更新或其他东西,但也许有人可以确认/证明我错了。

It is possible to access the store as an object in an external js file, I have also added a test to demonstrate the changes in the state.可以将 store 作为外部 js 文件中的对象访问,我还添加了一个测试来演示状态的变化。

here is the external js file:这是外部js文件:

import { store } from '../store/store'

export function getAuth () {
  return store.state.authorization.AUTH_STATE
}

The state module:状态模块:

import * as NameSpace from '../NameSpace'
/*
   Import everything in NameSpace.js as an object.
   call that object NameSpace.
   NameSpace exports const strings.
*/

import { ParseService } from '../../Services/parse'

const state = {
  [NameSpace.AUTH_STATE]: {
    auth: {},
    error: null
  }
}

const getters = {
  [NameSpace.AUTH_GETTER]: state => {
    return state[NameSpace.AUTH_STATE]
  }
}

const mutations = {
  [NameSpace.AUTH_MUTATION]: (state, payload) => {
    state[NameSpace.AUTH_STATE] = payload
  }
}

const actions = {
  [NameSpace.ASYNC_AUTH_ACTION]: ({ commit }, payload) => {
    ParseService.login(payload.username, payload.password)
      .then((user) => {
        commit(NameSpace.AUTH_MUTATION, {auth: user, error: null})
      })
      .catch((error) => {
        commit(NameSpace.AUTH_MUTATION, {auth: [], error: error})
      })
  }

export default {
  state,
  getters,
  mutations,
  actions
}

The store:店铺:

import Vue from 'vue'
import Vuex from 'vuex'
import authorization from './modules/authorization'

Vue.use(Vuex)

export const store = new Vuex.Store({
  modules: {         
    authorization    
  }                  
})                   

So far all I have done is create a js file which exports a function returning the AUTH_STATE property of authorization state variable.到目前为止,我所做的只是创建一个 js 文件,该文件导出一个返回authorization状态变量的AUTH_STATE属性的函数。

A component for testing:用于测试的组件:

<template lang="html">
    <label class="login-label" for="username">Username
        <input class="login-input-field" type="text" name="username" v-model="username">
    </label>
    <label class="login-label" for="password" style="margin-top">Password
         <input class="login-input-field" type="password" name="username" v-model="password">
    </label>
    <button class="login-submit-btn primary-green-bg" type="button" @click="login(username, password)">Login</button>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import * as NameSpace from '../../store/NameSpace'
import { getAuth } from '../../Services/test'

export default {
  data () {
    return {
      username: '',
      password: ''
    }
  },
  computed: {
    ...mapGetters({
      authStateObject: NameSpace.AUTH_GETTER
    }),
    authState () {
      return this.authStateObject.auth
    },
    authError () {
      return this.authStateObject.error
    }
  },
  watch: {
    authError () {
        console.log('watch: ', getAuth()) // ------------------------- [3]
      }
    },
    authState () {
      if (this.authState.sessionToken) {
        console.log('watch: ', getAuth()) // ------------------------- [2]
      }
    },
  methods: {
    ...mapActions({
      authorize: NameSpace.ASYNC_AUTH_ACTION
    }),
    login (username, password) {
      this.authorize({username, password})
      console.log(getAuth())             // ---------------------------[1]
    }
  }
}
</script>

On the button click default state is logged on to the console.在按钮上单击默认状态是登录到控制台。 The action in my case results in an api call, resulting a state change if the username - password combination had a record.在我的情况下,操作会导致 api 调用,如果用户名 - 密码组合有记录,则会导致状态更改。

A success case results in showing the console in authState watch, the imported function can print the changes made to the state.成功案例导致在authState watch 中显示控制台,导入的函数可以打印对状态所做的更改。

Likewise, on a fail case, the watch on authError will show the changes made to the state同样,在失败的情况下, authError上的authError将显示对状态所做的更改

For anyone wondering how to access a mutation from a javascript file, you can do the following:对于想知道如何从 javascript 文件访问突变的任何人,您可以执行以下操作:

import store from './store'
store.commit('mutation_name', mutation_argument);

Or for actions,或者对于行动,

store.dispatch('action_name', action_argument)
import store from './store'

and than然后

store.commit('mutation_name', mutation_argument)

if you use js file如果你使用js文件

You can also access actions like:您还可以访问以下操作:

import store from './store'
store.dispatch('action_name', action_argument)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM