天天看點

vuex簡單描述、用法

vuex的簡單描述

vuex: Vue.js 應用程式開發的狀态管理模式

store: 單一狀态樹

getter: 可以認為是 store 的計算屬性

mutation:

更改 Vuex 的 store 中的狀态的唯一方法是送出 mutation,同步

Action:

送出的是 mutation,而不是直接變更狀态。

Action 可以包含任意異步操作

Module:

每個子產品擁有自己的 state、mutation、action、getter

vuex的引用及方法定義

1、main.js中,将store注入根節點,每一個元件中就可以使用了

import store from './store'

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

2、store檔案夾中建立index.js内容如下

import Vue from 'vue'

// 引入vuex
import Vuex from 'vuex'

// 注冊vuex
Vue.use(Vuex)

// 定義類型
const types = {
  SET_AUTHENTICATED:"SET_AUTHENTICATED",
  SET_USER:"SET_USER"
}

// 定義資料狀态
const state = {
  isAuthenticated:false,
  user:{}
}

// 擷取資料
const getters = {
  isAuthenticated:state => state.isAuthenticated,
  user: state => state.user
}

// 修改狀态方法定義
const mutations = {
  // 設定是否授權,
  [types.SET_AUTHENTICATED](state,isAuthenticated){
    if(isAuthenticated) state.isAuthenticated = isAuthenticated;
    else state.isAuthenticated = false;
  },
// 設定user
  [types.SET_USER](state, user){
    if(user) state.user = user;
    else state.user = {};
  }
}

// 異步操作用于調用mutation
const actions = {
  setAuthenticated: ({commit}, isAuthenticated) => {
    commit(types.SET_AUTHENTICATED, isAuthenticated)
  },
  setUser: ({commit},user) => {
    commit(types.SET_USER,user)
  },
  // 登出--
  clearCurrentState:({commit}) => {
    commit(types.SET_AUTHENTICATED, false)
    commit(types.SET_USER,null)
  }
}

// 導出對象
export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})
           

使用:

擷取資料:

擷取之後可直接使用html中可以直接用{{user}}

export default {
    name:"head-nav",
    // 擷取vuex中user資料
    computed: {
        user(){
            return this.$store.getters.user
        }
    },
}
           

設定資料:

//設定vuex store
this.$store.dispatch("clearCurrentState");
           
vue