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实现同一个页面多个组件之间的通信:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

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

友情链接更多精彩内容