Javascript - Vue - vuex

vuex

這是一個與vue配套的公共數據管理工具,能夠將一些須要共享的數據保存到vuex中,以此方便項目中的任何組件均可以從vuex中獲得共享數據。cnpm i vuex -S 裝包html

讀取數據vue

//在main中導入vuex而後掛載在vue對象上
import Vuex from "vuex"
Vue.use(Vuex)

var store = new Vuex.Store({
    //state:數據存儲倉庫
    state: {

        txt: "hello"
    }
})
var vm = new Vue({
    el: "#box",      
    store: store 
})

如今能夠在項目中的任何能夠使用js的文件中訪問store vuex

<div id="box">
    {{$store.state.txt}}
</div>

操做數據npm

雖然能夠使用$store.state.txt=xx的方式直接操做數據,但vuex並不建議這樣作,更高級的方法是使用vuex的mutations,操做數據的代碼方法放在mutations中,而後經過$store調用操做方法處理數據。mutations內的方法最多接收兩個參數,第一個固定爲state,另外一個是自定義參數。瀏覽器

<div class="btn-2" @click="add">test</div>

var store = new Vuex.Store({
    //state:數據存儲倉庫
    state: {

        txt: "hello"
    },
    //代理執行對數據的操做
    mutations: {

        add(state) {
            state.txt += "worlld";
        }
    }
});

var vm = new Vue({
    el: "#box",      
    store: store,
    methods: {
        add: function () {
            this.$store.commit("add");
        }
    }
})

包裝數據app

若是須要對數據進行包裝處理,能夠使用getters,獲取數據的時候就再也不直接調用$store.state.xxide

var store = new Vuex.Store({
    //存儲
    state: {

        count: 0
    },
    //操做
    mutations: {

        add: function (state, num) {
            state.count += num;
        },
        remove: function (state, num) {
            state.count -= num;
        }
    },
    //包裝,能夠對倉儲的數據進行包裝或計算
    getters: {

        wrapperValue: function (state) {
            return "當前數量" + state.count;
        }
    }
});
//獲取包裝的數據:$store.getters.wrapperValue

持久化存儲工具

vue路由機制使不須要刷新瀏覽器地址就能夠靜態加載組件到客戶端頁面上顯示,而vuex默認的存儲機制也只是在不刷新的前提下存儲數據,若是向持久化存儲數據,則須要使用js原生的對象localStorage,將數據存儲在localStorage中,刷新瀏覽器頁面後須要從vuex的store中讀取數據,則能夠把localStorage的數據放到vuex中。post

<template>
    <div>
        <input type="text" ref="input">
        <button @click="add">持久化存儲</button>
        {{$store.state.x}}
    </div>
</template>
export default {
    methods: {
        add: function () {
            var x = this.$refs.input.value;
            this.$store.commit("add", x);
        }
    }
};

在main.js中學習

var x = localStorage.getItem("x") || ""; 
var store = new Vuex.Store({
    state: {
        x: x,//將本地存儲庫的數據放到vuex的倉儲中
    },

    mutations: {
        add: function (state, str) {
            state.+= str;
            localStorage.setItem("x", state.x);
        }         
    }
});

刷新瀏覽器後數據依然存在

localStorage.removeItem("key") //移除指定的數據
localStorage.clear() //移除全部數據

更多關於localStorage的信息,參考:localStorage使用總結

Javascript - 學習總目錄

相關文章
相關標籤/搜索