繁体   English   中英

使用插件并存储在中间件 [Nuxt]

[英]using a plugin and store in middleware [Nuxt]

我想编写一个中间件来检查用户的身份验证和权利。 我从我的商店获取身份验证详细信息:

//store/index.js
const state = () => ({
  auth: {
    isLoggedIn: false
    // and so on
  }
});

以及插件的权利:

//plugins/entitlement.js

  import axios from 'axios';
  export default (context, inject) => {
    const { env: { config: { entitlementUrl } }, store: { state: { auth: { access_token } } } } = context;
  const headers = { 
    Authorization: `Bearer ${access_token}`,
    'Content-Type': 'application/json' 
  };
  inject('entitlement', {
    isEntitled: (resourceId) => new Promise((resolve, reject) => {
      axios.get(`${entitlementUrl}/entitlements`, { headers, params: { resourceId } })
      .then(({ data }) => {
        resolve(data.Count > 0);
      })
      .catch((error) => {
        reject(error);
      });
    })
  };

这是我写的中间件,但它不起作用:

//middleware/isEntitled.js

export default function ({ app, store }) {
  if(store.state.auth.isLoggedIn){
    let isEntitled =  app.$entitlement.isEntitled('someId');
    console.log('entitled? ', isEntitled)
  }
}

然后我将它添加到我的配置中:

//nuxt.config.js
  router: {
     middleware: 'isEntitled'
  },

我收到未定义的错误isEntitled 我要做的就是检查应用程序的每个页面以查看用户是否有权? 我怎样才能做到这一点?

如果从plugin端看情况,可以这样做:

首先创建一个插件:

export default ({app}) => {
    // Every time the route changes (fired on initialization too)
    app.router.beforeEach((to, from, next) => {
        if(app.store.state.auth.isLoggedIn){
            let isEntitled =  app.$entitlement.isEntitled('someId');
            console.log('entitled? ', isEntitled)
        }
        return next();
    })
}

然后将plugin添加到您的nuxt.config.js文件中:

plugins: [
    '~/plugins/your-plugin.js',
],

暂无
暂无

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

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