Vue框架学习(4)--Vuex学习

1.Vuex介绍
2.安装和导入
3.Vuex模板
4.state使用
5.Mutation使用
6.Action使用
7.模块化读取数据
8.Vuex数据持久化

1.Vuex介绍
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式
它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化
Vuex文档:https://v3.vuex.vuejs.org/zh/
2.安装和导入
命令:npm install vuex 
在main.js中导入

# @/store/index Vuex  --Vux文件的路径
import index from '@/store/index'
app.use(index);
3.Vuex模板
# 文件名 index.js

# 模板一
import { createStore } from "vuex"
export default createStore({
    
    // 存放数假
    state: {},

    getters: {},

    // 同步操作
    mutations: {},

    // 异步操作
    actions: {},
    
    modules: {},
    })

# 模板二:模块化操作

    import { createStore } from "vuex"
    export default createStore({

    modules: {

        loginModule: {
            namespaced: true,
            state: {
                "name": "login",
                "age":"20"
            },},

        indexModule: {
            namespaced: true,
            state: {
                "name": "index",
                "age":"18",
            },

        }
    }
    
    },
    })
4.state使用
- state 存放数据,类似data()
  - 获取值Vuex中state的定义的值
  - 方法一:{{ this.$store.state.值的名称 }} 
     - eg:{{ this.$store.state.name }}
  - 方法二: {{值的名称}}  +  ...mapState([值的名称1、值的名称2、..])
     - eg: {{name}}  +   ...mapState(["age", "name", "price"])
  - 使用方法:
 ### xxx.vue
 <template>
     <div>{{ age }}</div>
     <div>{{ name }}</div>
     <div>{{ price }}</div>
     <div>{{ this.$store.state.name }}</div>
 </template>

 <script>
 import { mapState } from 'vuex'
 export default {
     
      //  需要放在computed中才可以执行
      computed: {
         ...mapState(["age", "name", "price"])
     }
 }
 </<script>


 ### xxx.js
 import { createStore } from "vuex"
 export default createStore({

 state: {
     "name": "abc",
     "age": 18,
     "price":20,
 },
 })
5.Mutation使用
- 更改Vuex中store状态的唯一方法
- 调用mutation中的方法: this.$store.commit(方法名)

### xxx.vue
methods: {
    addAge() {
        this.$store.commit('increment')
    },

    changeName() {
        this.$store.commit("changeUser", { "name": "xiaoming" })
    },
    
    addNewData() {
        this.$store.commit("addNewValue", "three billoin")
    },
},

### xxx.js
state: {
    "name": "abc",
    "age": 18,
     },

mutations: {
    
    // 默认会有state对象,通过对象.属性即可以修改state的值
    increment(state) {
        state.age++
    },
    
    // 有参数的格式
    updateAge(state, data) {
        state.age = data
    },
    
    // 对象的格式
    changeUser(state, { name }) { 
        state.name = name;
    },
}
6.Action使用
Action不建议直接修改State的值,得通过提交mutation来修改State的值
    Action可以包含任意异步操作
    用法:this.$store.dispatch(方法名)

 #### xxx.vue
  actionAddData() {
      this.$store.dispatch("addAgeByAction")
  }

  #### xxx.js

  state: {
      "age": 18,
      },

   mutations: {
      increment(state) {
          state.age++
      },
  }

  actions: {
      addAgeByAction(content) {
          content.commit("increment")
      }
7.模块化读取数据
#### xxx.vue
<template>
    <div>首页</div>
    <!-- <div>登录模块--{{ this.$store.state.loginModule.name }}</div> -->
    <div>登录模块读取--{{ name }}</div>
    <button @click="indexButton">首页按钮</button>
    <button @click="indexAction">首页action按钮</button>
</template>

<script>
import { useStore, mapState, mapMutations } from 'vuex'
export default {
    name: '',
    mounted(){
        // 获取对应模块的值
        console.log(this.$store.state.loginModule.name)
        console.log(this.$store)
    },

    methods:{
        indexButton(){
            // 提交到对应的模块方法: 模块名/对应的方法
            this.$store.commit("indexModule/loginAge")
        },

        indexAction(){
            // 提交到对应的模块方法: 模块名/对应的方法
            this.$store.dispatch("indexModule/loginaction")
        }
    },          

    computed:{
        // 模块名称,要读取的值
        ...mapState('loginModule',[ "name"])
    },
}
</script>

<style scoped>
</style>


#### xxx.js
import { createStore } from "vuex"
export default createStore({

    modules: {

        loginModule: {
            namespaced: true,
            state: {
                "name": "login",
                "age":"20"
            },},

        indexModule: {
            namespaced: true,
            state: {
                "name": "index",
                "age":"18",
            },
            mutations:{
                loginAge(){
                    console.log(111)
                }},

            actions:{
                loginaction(){
                    console.log(222)
                }}
        }




    }

})
8.Vuex数据持久化
- 事件监听操作:https://blog.csdn.net/handsomeAndHero/article/details/125315491

export default {
    name: '',
    //解决vuex数据在页面刷新被重置的问题 
    created() {

        //在页面加载时读取sessionStorage里的状态信息
        if (sessionStorage.getItem("store")) {
            this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(sessionStorage.getItem("store"))))
            console.log(this.$store.state.age)
            this.$store.commit("initdate", this.$store.state.age)
        }


        //在页面刷新时将vuex里的信息保存到sessionStorage里
        window.addEventListener("beforeunload", () => {
            sessionStorage.setItem("store", JSON.stringify(this.$store.state))
            console.log("beforeunload")
        })

        window.addEventListener("focusout", () => {
            sessionStorage.setItem("store", JSON.stringify(this.$store.state))
            console.log("focusout")
        })

        window.addEventListener("click", () => {
            sessionStorage.setItem("store", JSON.stringify(this.$store.state))
            console.log("click")
        })

        window.addEventListener("pagehide", () => {
            sessionStorage.setItem("store", JSON.stringify(this.$store.state))
            console.log("pagehide")
        })

    },

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。

文章标题:Vue框架学习(4)--Vuex学习

本文作者:伟生

发布时间:2023-05-27, 18:23:00

最后更新:2023-07-08, 15:01:04

原始链接:http://yoursite.com/2023/05/27/qianduan_04_vue_study_4_vuex/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏