前言
vuex的具體使用教程查看官網文檔 https://vuex.vuejs.org/zh/installation.html,這里只是記錄一下vuex在項目中具體的使用
簡單集成過程
創建vuex模塊文件
在項目的 src/ 目錄下創建 【store】文件夾,並在 src/store/ 目錄下創建 store.js. 這個js名稱可以按自己需要更改
模塊文件內容
在store.js中加入如下代碼
// src/store/store.js import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex) let store = new Vuex.Store({ // 1. state state:{ city:"城市名", event:[], //存儲websocket傳輸過來的數據 }, getters:{ getEvent(state){ return state.city; } }, mutations:{ setEvent(state, event){ state.event.push(event) } }, }); export default store;
這里大概簡述一下vuex.Store參數中的幾個屬性:
- state: 存儲變量的地方,我們平時定義的變量都放到這里面, 外部可以通過 this.$store.state.* 去獲取存儲的變量值
- getters: 獲取變量的時候添加的過濾器,用getter里面定義的函數去獲取state數據時,可以對state里的數據提前進行加工處理
- mutations: 定義一個函數去修改state里面的值,直接修改state里的值vue會監聽不到數據變化,所以通過mutations里定義函數來操作state里的數據。只能同步處理。
- actions:定義函數去調用mutations的,這樣又加了一層的目的是為了讓mutations能處理異步的請求,如果項目中對state都是同步處理,就不用加這一層
掛載到vue
在項目入口main.js中加入如下代碼
// 1. 導入到main.js中 import store from "./store/store" ... //2. 掛載到vue對象上 new Vue({ el: '#app', router, store, //主要看這一行 components: { App }, template: '<App/>' })
vuex基本使用
1. js模塊中調用
//===== 獲取state的值===== //直接獲取方法 this.$store.state.city //通過getters定義函數獲取 //這里可以傳入參數,但是由於getters定義函數時第一個參數必須是state,所以這里傳入的參數在getters里從第二個開始算起。(我也不知道怎么說,看文檔去吧) this.$store.getters.getEvent() //===== 設置state的值===== this.$store.commit("setEvent", eventDate)
2. html中調用
去掉this,剩下的和js里使用一樣, 例如: {{ $store.store.state.event }}
處理