简体   繁体   English

VueX:如何在页面加载时调用 action.js 方法?

[英]VueX: How to call a action.js method on page load?

I'm super new to nuxt and have picked up a large project.我是 nuxt 的超级新手,并且已经开始了一个大项目。 I can't work out how other views are doing it, but I want to run an axios on page load, could someone help me?我无法弄清楚其他视图是如何做的,但我想在页面加载时运行 axios,有人可以帮助我吗?

The way this project is structured is it has a store folder (guessing this is vuex), and get a getter.js, mutations.js, index.js, state,js, and actions.js (apologies if this is the natural way) not sure if the way my project does it is a custom design pattern or if its just the goto way with nuxt / vuex这个项目的结构方式是它有一个 store 文件夹(猜测这是 vuex),并获得一个 getter.js、mutations.js、index.js、state、js 和 actions.js(如果这是自然的方式,请道歉) 不确定我的项目的方式是自定义设计模式还是只是使用 nuxt / vuex 的 goto 方式

So far I have tried this,到目前为止,我已经尝试过这个,

computed: {
  plans: 'accountBilling/fetch',
},

But I believe this is for the getters.js file?但我相信这是针对 getters.js 文件的?

I have an actions.js file, and want to call and receive the response from fetch on page load?我有一个 actions.js 文件,想在页面加载时调用和接收来自 fetch 的响应?

export default {
  async fetch({ commit }, { account_id }) {
    return await this.$axios.get(`/accounts/billing/plans`)
      .then(response => { commit('setPlans', response.data); response.data })
      .catch(error => { throw error })
  },
}

In your root component, in the mounted hook: 在您的根组件中,在mounted挂钩中:

mounted() {
  this.$store.dispatch("fetch");
}

And then to get plans: 然后获得计划:

computed: {
  plans() { return this.$store.state.plans; }
}

In Nuxt.js you don't really have a root component as such.在 Nuxt.js 中,你并没有真正的根组件。 You could use the index.vue component but if someone enters your web app via a different page the function won't be called.您可以使用 index.vue 组件,但如果有人通过不同的页面进入您的网络应用程序,则不会调用该函数。 So I found the best way is to use the middleware function that is baked into Nuxt.所以我发现最好的方法是使用烘焙到 Nuxt 中的中间件功能。

First, create a middleware folder in your root (if you don't have one already) and add a file onload.js .首先,在您的根目录中创建一个middleware文件夹(如果您还没有)并添加一个文件onload.js

Add the below code in the file:在文件中添加以下代码:

export default function ({store}) {
    store.dispatch('fetchMenu')
    // Or whatever action you want to call
  }

Then add this middleware to your nuxt.config.js然后将此中间件添加到您的 nuxt.config.js

...
 router: {
    middleware: ['onload']
  },
...

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

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