简体   繁体   English

基于值重定向的 Vue 路由器和 vuex 问题

[英]Vue router and vuex issue with redirecting based on a value

I have a Vue application that I am trying to have it that when the user has not paid and trial is over they are redirected to /billing and displayed an error message.我有一个 Vue 应用程序,我正在尝试使用它,当用户未付款且试用期结束时,它们将被重定向到/billing并显示一条错误消息。 I also would like it so that if they have paid or are still in their trial period that they can use the application.我也希望这样,如果他们已经付款或仍在试用期,他们可以使用该应用程序。

storeUser code in my store.js我的 store.js 中的 storeUser 代码

storeUser(state, user) {
      state.user = user
      state.isPaid = user.isPaid
      state.isTrial = user.isTrial
 },

data passed into storeUser as 'user'数据作为“用户”传递给 storeUser

{
  name: "Joe",
  isPaid: false,
  isTrial: false
}

Data showing in my vuex store using the chrome vui extention使用 chrome vui 扩展在我的 vuex 商店中显示的数据

{
  name: "Joe",
  isPaid: null,
  isTrial: null
}

Not sure why the data is being input wrong since I can console.log the correct data in the storeUser function.不知道为什么数据输入错误,因为我可以在 storeUser 函数中 console.log 正确的数据。 However if I look into the user portion I can see it as the correct false values.但是,如果我查看用户部分,我可以将其视为正确的错误值。 When I try to specify this in the code below for the vue router it says that is can't read it because it's null.当我尝试在下面的代码中为 vue 路由器指定它时,它说无法读取它,因为它为空。 I assume this is just an async issue.我认为这只是一个异步问题。

state in store.js store.js 中的状态

state: {
    token: null,
    isPaid: null, 
    isTrial: null,
    error: {
      registerErrorMessage: '',
      loginErrorMessage: '',
      resetError: ''
    },
    user: null
  }

main.js which contains my vue router main.js 包含我的 vue 路由器

} else if(to.path != '/billing' && !(store.state.isPaid && store.state.isTrial)) {
    next({
      path: '/billings',
      query: {
         paid: false,
      }
  })

Can anyone spot a potential issue or maybe a solution to my issue?任何人都可以发现潜在的问题或解决我的问题吗? This code should be enough to reproduce the issue though if missing I can provide more, there is no public repo to show the rest of the code in.这段代码应该足以重现问题,但如果缺少我可以提供更多,没有公共存储库来显示其余代码。

EDIT** So something weird happened.. I am now seeing more correct data than before (isPaid and isTrial are valid) however I'm still not able to go to other routes now.编辑** 所以发生了一些奇怪的事情..我现在看到比以前更正确的数据(isPaid 和 isTrial 是有效的)但是我现在仍然无法去其他路线。 Adding output of store.state at the beginning of my beforeEach在我的 beforeEach 开头添加 store.state 的输出

{
  token: 'random string',
  isPaid: true,
  isTrial: false,
  error: {},
  user: {
    name: "Joe",
    isPaid: true,
    isTrial: false
  }
}

EDIT 2**编辑 2**

storeUser({commit, state}) {
      if(!state.token) return
      axios.get('/user/userInfo')
        .then(res => {
          if(res.data.success) {
            commit('storeUser', {
              name: res.data.user.name,
              isPaid: res.data.user.company.stripe.isPaid,
              isTrial: res.data.user.company.stripe.isTrial
            })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

EDIT 3** Here is my whole vue route from main.js编辑 3** 这是我从 main.js 开始的整个 vue 路线

router.beforeEach((to, from, next) => {
  store.dispatch('tryAutoLogin')
  console.log(store.state) // this is test only not for prod
  if(!store.state.token && (to.path == '/login' 
    || to.path == '/signup' 
    || to.path == '/forgot' 
    || to.path == '/resend' 
    || to.path.includes('/confirmation/'))) 
  {
    return next()
  } else if (to.path == '/signup') {
    return next({ query: {plan: from.query.plan }})
  } else if(to.path != '/billing' && !(store.state.isPaid && store.state.isTrial)) {
    next({
      path: '/billing',
      query: {
         paid: false,
      }
  })
  } else if(store.state.token) {
    return next()
  } else {
    return next('/login')
  }
})

You can see I do the auto login which just checks if a token exists or not that's it.你可以看到我做了自动登录,它只是检查令牌是否存在。 It's not related to the issue.它与问题无关。

EDIT 4**编辑 4**

I have an idea but not sure how to implement it.. Use promises to make sure the data is right.我有一个想法,但不确定如何实现它.. 使用承诺来确保数据是正确的。 My confusion on the promise part is getting them to work together.我对承诺部分的困惑是让他们一起工作。 So I'm think authUser mutation then somehow make the storeUser action a promise that I can resolve in my beforeEach所以我认为authUser突变然后以某种方式使storeUser操作成为我可以在我的 beforeEach 中解决的承诺

Actions行动

tryAutoLogin({commit, dispatch}) {
   const token = localStorage.getItem('token')
   if(!token) {return}
   commit('authUser',{
     token
   })
   dispatch('storeUser')
},


storeUser({commit, state}) {
      if(!state.token) return
      axios.get('/user/userInfo')
        .then(res => {
          if(res.data.success) {
            commit('storeUser', {
              name: res.data.user.name,
              companyName: res.data.user.company.companyName,
              role: res.data.user.role,
              isPaid: res.data.user.company.stripe.isPaid,
              isTrial: res.data.user.company.stripe.isTrial
            })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },


Mutations突变

authUser(state, userData) {
  state.token = userData.token
},
storeUser(state, user) {
  state.user = user
  state.isPaid = user.isPaid
  state.isTrial = user.isTrial
},

Looks like you have a lot of duplicate and confusing code.看起来您有很多重复且令人困惑的代码。

Why is there 2 of isPaid and isTrial in the state?为什么状态中有两个isPaidisTrial

You also did not use the name property you provided to commit function.您也没有使用您提供的name属性来commit功能。

The commit提交

commit('storeUser', {
    name: res.data.user.name,
    isPaid: res.data.user.company.stripe.isPaid,
    isTrial: res.data.user.company.stripe.isTrial
});
const store = new Vuex.Store({
    state: {
        userName: '',
        isPaid: false,
        isTrial: false,
    },
    mutations: {
        storeUser(state, data) {
            state.userName = data.name;
            state.isPaid = data.isPaid;
            state.isTrial = data.isTrial;
        },
    },
});

Now you access the state store.state.isPaid and store.state.isTrial .现在您访问状态store.state.isPaidstore.state.isTrial

You can see a working example at this jsfiddle .你可以在这个jsfiddle看到一个工作示例。 If you open up the console you can see how the current state is logged.如果您打开控制台,您可以看到当前状态是如何记录的。

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

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