vuex--基本使用

vuex的作用

vuex来保存我们需要管理的状态值,值一旦被修改,所有引用该值的地方就会自动更新,解决vue中各个组件之间传值和通信的问题

vuex的使用

  • 安装vuex:
    npm install vuex --save

  • 我们在项目的src目录下新建一个目录store,在该目录下新建一个index.js文件,我们用来创建vuex实例,然后在该文件中引入vue和vuex,创建Vuex.Store实例保存到变量store中再导出

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        count: 1
    }
})

export default store

<font color=red>注意引入的vue和vuex字母的大小写,v都是小写,如果写成大写就无法引入</font>

  • 我们在main.js文件中引入该文件,在文件里面添加 import store from ‘./store’;,再在vue实例全局引入store对象
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    el: '#app',
    store,
    router,
    components: { App },
    template: '<App/>'
})

store跟router类似,如果import进来的模块名不叫store,应该这样写:

import Vue from 'vue'
import App from './App'
import router from './router'
import MyStore from './store'

Vue.config.productionTip = false
Vue.prototype.$appName = { name: 'main' }

/* eslint-disable no-new */
new Vue({
    el: '#app',
    store: MyStore,
    router,
    components: { App },
    template: '<App/>',


})

在任意模板中就可以使用store里面的变量了:

    <h1>{{ this.$store.state.count }}</h1>
  • Getters:
    Getter相当于vue中的computed计算属性,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算,这里我们可以通过定义vuex的Getter来获取,Getters 可以用于监听、state中的值的变化,返回计算后的结果
    它的作用主要是用来派生出一些新的状态。比如我们要把state状态的数据进行一次映射或者筛选,再把这个结果重新计算并提供给组件使用
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        count: 1
    },
    getters: {
        getCount: function(state) {
            return state.count + 1;
        }
    }
})

export default store
 <div>{{this.$store.getters.getCount}}</div>

注意getCount不要加括号

  • Mutations:
    如果需要修改store中的值唯一的方法就是提交mutation来修改
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        count: 1
    },
    getters: {
        getCount: function(state) {
            return state.count + 1;
        }
    },
    mutations: {
        add(state) {
            state.count = state.count + 1;
        },
        reduce(state) {
            state.count = state.count - 1;
        }
    }

})

export default store
<template>
    <div>
         <div>{{this.$store.state.count}}</div>
         <div>{{this.$store.getters.getCount}}</div>
         <button @click="add">加</button> 
         <button  @click="reduce">减</button>
         <div @click="gotoTest2">goto test2</div>
    </div>
</template>
<script>
export default {
    methods:{
        changeName(){
            this.$appName.name = "test1"
        },
        gotoTest2(){
            this.$router.push({name:"Test2"})
        },
        add(){
            this.$store.commit("add")
        },

        reduce(){
            this.$store.commit("reduce")
        }
    },
}
</script>

  • 也可以使用actions来修改值
import Vue from 'vue'
import Vuex from 'vuex'
import { isContext } from 'vm';
Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        count: 1
    },
    getters: {
        getCount: function(state) {
            return state.count + 1;
        }
    },
    mutations: {
        add(state) {
            state.count = state.count + 1;
        },
        reduce(state) {
            state.count = state.count - 1;
        }
    },
    actions: {
        addFun(context) {
            context.commit("add")
        },
        reduceFun(context) {
            context.commit("reduce")
        }
    }

})

export default store

这里的context相当于上面的this.$store

 addFun(context) {
            context.commit("add")
        },

可以等效写成这样:

 addFun({ commit }) {
           commit("add")
        },

组件中使用dispatch替代commit:

<template>
    <div>
         <div>{{this.$store.state.count}}</div>
         <div>{{this.$store.getters.getCount}}</div>
         <button @click="add">加</button> 
         <button  @click="reduce">减</button>
         <div @click="gotoTest2">goto test2</div>
    </div>
</template>
<script>
export default {
    methods:{
        changeName(){
            this.$appName.name = "test1"
        },
        gotoTest2(){
            this.$router.push({name:"Test2"})
        },
        add(){
            this.$store.dispatch("addFun")
        },

        reduce(){
            this.$store.dispatch("reduceFun")
        }
    },
}
</script>

  • 使用参数:
<template>
    <div>
         <div>{{this.$store.state.count}}</div>
         <div>{{this.$store.getters.getCount}}</div>
         <button @click="add">加</button> 
         <button  @click="reduce">减</button>
         <div @click="gotoTest2">goto test2</div>
    </div>
</template>
<script>
export default {
    methods:{
        changeName(){
            this.$appName.name = "test1"
        },
        gotoTest2(){
            this.$router.push({name:"Test2"})
        },
        add(){
            this.$store.dispatch("addFun",2)
        },

        reduce(){
            this.$store.dispatch("reduceFun",2)
        }
    },
}
</script>

import Vue from 'vue'
import Vuex from 'vuex'
import { isContext } from 'vm';
Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        count: 1
    },
    getters: {
        getCount: function(state) {
            return state.count + 1;
        }
    },
    mutations: {
        add(state, n) {
            state.count = state.count + n;
        },
        reduce(state, n) {
            state.count = state.count - n;
        }
    },
    actions: {
        addFun(context, n) {
            context.commit("add", n)
        },
        reduceFun(context, n) {
            context.commit("reduce", n)
        }
    }

})

export default store
  • 在action中,可以这样访问:context.state.count context.getters.getCount

  • 在组件1里改变的值,通过路由跳转到组件2时,会同步更新,取改变后的值

  • store的在vue中的初始化过程
    Vue.use(Vuex)时,跟所有插件一样,会调用Vuex的的install方法,注册一个$store属性
    Vue.prototype.$store
    在main.js里面,我们在根组件里传入了一个store对象,Vue会通过调用Vuex以下方法把这个对象赋值给$store:
function vuexInit () {
  const options = this.$options
  // store injection
  if (options.store) {
    this.$store = options.store
  } else if (options.parent && options.parent.$store) {
    this.$store = options.parent.$store
  }
}

这样,我们后面使用this.$store实际操作的是store对象,因为Vue回调Vuex的vuexInit时,store这个变量名是写死的,所以根组件中传入的变量名必须是store,当然也可以用它指向其他变量,比如:
store: MyStore
router也是类似的道理

  • vuex用于同一个页面各个组件之间传递数据,它使用内存保存变量,浏览器刷新后,保存的数据也将失效,本身并不适合做全局数据保存,所以如果需要刷新时还能使用保存的数据,需要结合sessionstorage或localstorage
getters:{
    userInfo(state){
        if(!state.userInfo){
            state.userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
        }
        return state.userInfo
    }
},
mutations:{
    LOGIN:(state,data) => {
        state.userInfo = data;
        sessionStorage.setItem('userInfo',JSON.stringify(data));
    },
    LOGOUT:(state) => {
        state.userInfo = null;
        sessionStorage.removeItem('userInfo');
    }
},

下面这个github上的小游戏:
https://github.com/leftstick/vue-memory-game
就是用vuex实现同一个页面多个组件之间的通信:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容

  • 配置 vuex 和 vuex 本地持久化 目录 vuex是什么 vuex 的五个核心概念State 定义状态(变量...
    稻草人_9ac7阅读 873评论 0 5
  • 1.简介 1.1Vuex是什么 Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。 Vuex其实是管...
    MissWang1阅读 391评论 0 2
  • 在 vue 开发中,组件通信一直是一大痛点。 当项目是很简单的 SPA 或者多入口项目时,可以靠着 vue 自带的...
    若年阅读 1,628评论 0 4
  • Vuex是什么? 按vuex官网的说法,vuex是专为vue.js开发的状态管理模式,它采用集中式存储管理应用的所...
    千里一线缘阅读 439评论 0 0
  • vuex的使用 一、配置 1、在store/index中配置 2、导入maiin.js,传入根组件中 二、stat...
    风的记忆乀阅读 1,360评论 0 0