VueX 安装使用(含TypeScript)

内容简介:

  1. 借鉴 了 FluxRedux、 The Elm Architecture
  2. 专为 Vue.js 设计 的状态管理模式
  3. 集中式存储和管理应用程序中所有组件的状态
  4. Vuex 也集成到 Vue 的官方调试工具
  5.  一个 Vuex 应用的核心是 store(仓库,一个容器),store 包含着你的应用中大部分的状态 (state)

安装引入:

直接引入:

<script src="/path/to/vue.js"></script>

<script src="/path/to/vuex.js"></script>



NPM 引入:

npm install vuex@next --save



Yarn 引入

yarn add vuex@next --save

注册:

TS:

在 store/index.ts 中的modules: 中注册

import { createStore } from 'vuex'

export default createStore({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  },
  
})

JS:

import Vue from 'vue'

import App from './App.vue'


配置 VueX
import store from './store'

new Vue({
  store,
  render: h => h(App)
}).$mount('#app')

基础内容:

 

state:

获取 token 状态   state(设置数据,对象) 设置 本地存储

state: {
    token: localStorage.getItem('token') || ''
  },

Mutations

Mutations 突变 注册 状态改变事件:

创建 token

mutations: {
    setToken(state: any, token: any) {
      state.token = token
      localStorage.setItem('token', token)
    }
  },

Actions:

Actions 行动 提交突变事件

第一种:
  actions: {
    actToken({ commit }: any, user: any) {
      commit('setToken', user)
      console.log(user.name);

      console.log("actions");
    }
  }
第二种
    actions: {
    actToken(context: any, user: any) {
      context.commit('setToken', user)
    }
  }

使用 commit 与 dispatch  修改存储的数据:

commit('A',B) ||  context.commit('A',B)

  1. A 为 调用的突变 函数名
  2. B 为 键值
  3. 在 Actions 中提交结束事件

C.dispatch('A',B)

A 为 调用的 Actions 中的方法名

如果 有   namespace: true,

    loginStore.dispatch("loginToken/actToken", form.value);

     没有

    loginStore.dispatch("actToken", form.value);

B 为 传入的 键值

设置 localstorage
     loginStore.dispatch("actToken", form.value);

C 为 导入的 store 包 实例的 对象

导包 useStore 从 vuex
     import { useStore } from "vuex"; 
实例化 store 对象
     const loginStore = useStore();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现 token 的方法,可以参考下面的代码实现: 在 `src/store` 目录下新建 `auth` 目录,用于存放认证相关的代码。 ```typescript // src/store/auth/state.ts export interface AuthState { token: string | null; } export const state: AuthState = { token: localStorage.getItem('token') || null, }; ``` ```typescript // src/store/auth/mutations.ts import { AuthState } from './state'; export const mutations = { setToken(state: AuthState, token: string) { state.token = token; localStorage.setItem('token', token); }, clearToken(state: AuthState) { state.token = null; localStorage.removeItem('token'); }, }; ``` ```typescript // src/store/auth/actions.ts import { ActionContext } from 'vuex'; import { AuthState } from './state'; import { RootState } from '../root-state'; export const actions = { async login(context: ActionContext<AuthState, RootState>, payload: { username: string; password: string }) { // 发送登录请求 const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(payload), }); if (response.ok) { const { token } = await response.json(); context.commit('setToken', token); } else { throw new Error('登录失败'); } }, logout(context: ActionContext<AuthState, RootState>) { context.commit('clearToken'); }, }; ``` ```typescript // src/store/auth/index.ts import { Module } from 'vuex'; import { AuthState, state } from './state'; import { mutations } from './mutations'; import { actions } from './actions'; import { RootState } from '../root-state'; export const auth: Module<AuthState, RootState> = { namespaced: true, state, mutations, actions, }; ``` 然后,在 `src/store` 目录下新建 `index.ts` 文件,用于创建 store 实例。 ```typescript // src/store/index.ts import { createStore } from 'vuex'; import { auth } from './auth'; import { RootState } from './root-state'; export const store = createStore<RootState>({ modules: { auth, }, }); ``` 最后,在 `main.ts` 中引入 store 实例,并在根组件中注入。 ```typescript // main.ts import { createApp } from 'vue'; import App from './App.vue'; import { store } from './store'; const app = createApp(App); app.use(store); app.mount('#app'); ``` 这样,就可以在组件中通过 `this.$store.state.auth.token` 访问 token 了。在登录成功后,通过 `this.$store.dispatch('auth/login', { username, password })` 更新 token;在注销时,通过 `this.$store.dispatch('auth/logout')` 清除 token。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值