Search code examples
javascriptvue.jsnuxt.jsvuex

I want to use this. $ axios with Vuex constants


What I want to come true

I use this.$axios many times, so I tried to put it in a constant, but it doesn't work. I read the official docs but didn't understand. Is it because this isn't available in the Nuxt.js lifecycle?

Code

url.js

export const AXIOS_POST = this.$axios.$post

export const POST_API = '/api/v1/'

export const POST_ITEMS_API = '/api/v1/post_items/'

Vuex

import * as api from './constants/url.js'  // url.js in this.

export const state = () => ({
  list: [],
  hidden: false
})

export const mutations = {
  
  add (state, response) {
    state.list.push({
      content: response.content,
      status: response.status
    })
  },


  remove (state, todo) {
    state.list.splice(state.list.indexOf(todo), 1)
  },


  edit (state, { todo, text }) {
    state.list.splice(state.list.indexOf(todo), 1, { text })
  },


  toggle (state, todo) {
    todo.status = !todo.status
  },

  cancel (state, todo) {
    todo.status = false
  },

  // アクション登録パネルフラグ
  switching (state) {
    state.hidden = !state.hidden
  }
}

export const actions = {

  post ({ commit }, text) {

//I want to use it here

    this.$axios.$post(api.POST_ITEMS_API + 'posts', {
      post_items: {
        content: text,
        status: false
      }
    })
      .then((response) => {
        commit('add', response)
      })
  }
}


Error

Uncaught TypeError: Cannot read property '$axios' of undefined


Solution

  • Since your file is located into a constants directory, you should probably use some .env file.
    Here is a guide on how to achieve this in Nuxt: https://stackoverflow.com/a/67705541/8816585


    If you really want to have access to it into a non .vue file, you can import it as usual with something like this

    /constants/url.js

    import store from '~/store/index'
    
    export const test = () => {
      // the line below depends of your store of course
      return store.modules['@me'].state.email
    }
    

    PS: getters, dispatch and everything alike is available here.

    Then call it in a page or .vue component like this

    <script>
    import { test } from '~/constants/url'
    
    export default {
      mounted() {
        console.log('call the store here', test())
      },
    }
    </script>
    

    As for the lifecyle question, since the url.js file is not in a .vue file but a regular JS one, it has no idea about any Vue/Nuxt lifecycles.