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 - 学习总目录

相关文章
相关标签/搜索