Vuex 状态管理模式(使用)

一、Vuex简介

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

二、使用

1.安装依赖

  1. 情景1:在使用vueCli创建项目时勾选Vuex这个选项,项目会自动引入Vuex
  2. 情景2:在使用vue-cli创建项目时未勾选Vuex,此时需要安装Vuex,安装步骤如下:

首先,进入到创建项目的根目录下 使用 `npm install --save vuex`命令进行安装;如果网速较慢可使用cnpm install --save vuex

安装完成后项目目录如下:

|__ node_modules
|__ public
|__ src
     |_ assest
     |_ components
            |_Hello.vue
     |_ store
            |_index.js
     |_ view
           |_HomeView.vue
           |_AboutView.vue      

2.使用

store中index.js中:

import { createStore } from 'vuex'

export default createStore({
  state: {
    count:10,
  },
})

main.js文件Vuex挂载到vue实例中

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

Vue.config.productionTip = false

new Vue({
  el: '#app',
  store,  //创建的Vuex实例挂载到这个vue实例中
  render: h => h(App)
})

3.store 在组件中使用

在store文件夹下index.js中定义一个count

state:{
    count:10;
}

在组件中读取count

  • 方法一:直接读取显示在页面
<template>
    <div>
        <p>{{ this.$store.state.count }}</p>
    </div>
</template>
  • 方法二:使用computed 计算属性读取 
<template>
    <div>
        <p>{{ getCount }}</p>
    </div>
</template>

<script>
export default{
    computed:{
        getCount(){
            return this.$store.state.count
        }
    }
}
</script>
  • 方法三: 使用mapState辅助函数
<template>
    <div>
        <p>{{ getCount }}</p>
    </div>
</template>

<script>
import { mapState } from "vuex" //引入mapState
export default{
    computed:{
        ...mapState(['count']),
        getCount(){
            return this.count
        }
    }
}
</script>

4.Mutation

官网定义:更改Vuex的store中的状态的唯一方法是提交mutation

通俗的理解:mutation是用来改变store中状态值

使用如下:

  • 情景一 :不携带参数

在store文件夹下的index.js中定义mutation (以改变上面count的值为例)

mutations: {
    addCount(state){    //对count执行加1的操作
      state.count += 1;
    },
    delCount(state){
      state.count -= 1; //对count执行减1的操作
    }
}

在组件中使用mutation 

<template>
    <div>
        <p>{{ getCount }}</p>
        <button @click="addHander">增加</button>
        <button @click="delHander">减少</button>
    </div>
</template>

<script>
export default{
    computed:{
        getCount(){
            return this.$store.state.count
        }
    },
    methods:{
        addHander(){
           this.$store.commit("addCount")     
        },
        delHander(){
            this.$store.commit("delCount")
        }
    }    
}
</script>
  •  情景二 携带参数

增加一个输入框,将用户输入的值作为count增加减少的对象

在store文件夹下的index.js中定义mutation (以改变上面count的值为例)

mutations: {
    addCount(state,num){    //对count执行加1的操作
      state.count += num;
    },
    delCount(state, num){
      state.count -= num; //对count执行减1的操作
    }
}

在组件中使用

<template>
    <div>
        <p>{{ getCount }}</p>
        <input type="text" v-model="num">
        <button @click="addHander">增加</button>
        <button @click="delHander">减少</button>
    </div>
</template>

<script>
export default{
    data(){
        return{
            num:""
        }    
    },
    computed:{
        getCount(){
            return this.$store.state.count
        }
    },
    methods:{
        addHander(){
           this.$store.commit("addCount",parseInt(this.num))     
        },
        delHander(){
            this.$store.commit("delCount",Number(this.num))
        }
    }    
}
</script>
  • 情景三:携带对象类型参数

     在store文件夹下的index.js中定义mutation (以改变上面count的值为例)

mutations: {
    addCount(state,obj){    //对count执行加1的操作
      state.count += obj.num;
    },
    delCount(state, obj){
      state.count -= obj.num; //对count执行减1的操作
    }
}

在组件中使用

<template>
    <div>
        <p>{{ getCount }}</p>
        <input type="text" v-model="num">
        <button @click="addHander">增加</button>
        <button @click="delHander">减少</button>
    </div>
</template>

<script>
export default{
    data(){
        return{
            num:""
        }    
    },
    computed:{
        getCount(){
            return this.$store.state.count
        }
    },
    methods:{
        addHander(){
           this.$store.commit("addCount",{
            num: parseInt(this.num)
            })     
        },
        delHander(){
            this.$store.commit("delCount",{
            num:Number(this.num)
            })
        }
    }    
}
</script>
  • 情景4 使用mapMutations辅助函数

首先,在组件中引入mapMutations函数 

<template>
    <div>
        <p>{{ getCount }}</p>
        <input type="text" v-model="num">
        <button @click="addHander">增加</button>
        <button @click="delHander">减少</button>
    </div>
</template>

<script>
import { mapState, mapMutations } from "vuex" //引入mapState
export default{
    data(){
        return{
            num:""
        }
    },
    computed:{
        ...mapState(['count']),
        getCount(){
            return this.count
        }
    },
    methods:{
        ...mapMutations(["addCount","delCount"]),
        addHander(){
            this.addCount({
                num: parseInt(this.num)
            })
        },
        delCount(){
            this.delCount({
                num: Number(this.num)
            })
        }
    }
}
</script>

5.Action 

Action类似于Mutation但不同点在于:Action可以处理异步操作

state:{
    count:10,
    navInfo:[]
}

action:{
  asyncUpdate(context){
     axios.get("网络请求接口").then(res=>{
        if(res.status === 200){
          context.commit("navInfo",res.data.banner)
        }else{
          context.commit("navInfo",[])
        }
      }).catch(err=>{
        console.log(err)
      })
    }
}

在组件中使用

  • 情景一:直接使用
<template> 
<div>    
    <ul>
        <li v-for="(item,index) in banner" :key="index">
            <p>{{item.title}}</p>
        </li>
    </ul>
    <button @click="getInfo">获取数据</button>
</div>
</template>

<script>
    export default{
        medthod:{
            getInfo(){
                this.$store.dispatch("asyncUpdate")
            }
        }
    }    
</script>
  • 情景2:使用mapActions辅助函数
<template> 
<div>    
    <ul>
        <li v-for="(item,index) in banner" :key="index">
            <p>{{item.title}}</p>
        </li>
    </ul>
    <button @click="getInfo">获取数据</button>
</div>
</template>

<script>
   import { mapActions } from "vuex"
    export default{
        medthod:{
            ...mapActions(['asyncUpdate'])
            getInfo(){
                this.asyncUpdate()
            }
        }
    }    
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值