在 Vue 中将数据从 child 传递到 child

Pass data from child to child in Vue

所以..在我的申请中,在 Authentication 章节,我有一些问题。

首先我有多个 components/routes,其中两个是 registerlogin

Register 工作正常,使用我的 api 作为响应,我得到一个 usernameaccount_id,它们都存储在数据库中。

当尝试 log in 时,作为响应,我得到 usernametoken.. 现在,当我访问我网站中的其他路由时,只有您登录后,我需要检测是否存在令牌。我怎样才能像一个具有 token 值的全局变量一样可以被其他组件轻松访问?

将您的令牌存储在 cookie / localstorage 中,如果您使用 vuex,您也可以将其存储在状态中。

如果您使用 Axios 或任何其他工具来处理 ajax 请求,您可以在 headers 中传递您的令牌,然后从 cookie / localstorage 中获取它。

state: {
   token: Cookie.getJSON('token') || null,
},
mutations: {
  setToken: (state, data) => {
    state.token = data
    Cookie.set('token', data)
  }
},
actions: {
  setToken (context, data) {
    context.commit('setToken', data.token)
  }
}

检查这个 - https://www.npmjs.com/package/js-cookie