zoukankan      html  css  js  c++  java
  • vuex的使用

    一、在项目中导入vuex

    ·npm install vuex 下载vuex

    ·在src文件夹下创建文件store、在store下 创建index.js 并输入 如图

    ·在main.js中引入 store文件 并在vue根实例上导入store  如图:

    这部分可以在vue官网中查看

    二、获取vuex中的值

    this.$store.state.值的键名

    (如:this.$store.state.Name)

    三、改变vuex中的值

     (3.1部分可以跳过直接看3.2,也可以做了解)

    3.1 在vue文件的事件中 this.$store.dispatch(‘事件名’,参数):如

    this.$store.dispatch('changeName',e)

    export default new Vuex.Store({

        state: {

            Name: '名字'

        },

        actions:{

            changeName (ctx, e) {

                ctx.commit('changeName2',e)

            }

        },

        mutations: {

            changeName2 (state, e) {

                state.Name = e

            }

        }

    })

    3.2、 跳过actions 组件可以直接调用mutations传值

    this.$store.commit ('changeName',e)

    store/index.js中:

    export default new Vuex.Store({

        state: {

            Name: '名字'

        },

        mutations: {

            changeName (state, e) {

                state.Name = e

            }

        }

    })

    然后调用的时候直接输入 xxx = this.$store.state.Name  就获取到啦

    3.3、 但是有的时候  页面一刷新 vuex中保存的值就清空了,这时我们就配合localStorage来保存我们的值,具体怎么实现的细节就不写了直接上例子:

    (try_catch是用来防止浏览器不兼容的问题,由于项目小所以state和mutation的部分没有分两个页面来写)

    import Vue from 'vue'

    import Vuex from 'vuex'

    Vue.use(Vuex)

     

    let lng = 120.2 ,lat = 36.5'//

    try {

      if (localStorage.lng) {

        lng = localStorage.lng

      }

      if (localStorage.lat) {

        lat = localStorage.lat

      }

    } catch (e) {}

    //调用时设置  this.$store.commit ('changeName',e)   获取时:this.$store.state.Name

    export default new Vuex.Store({

      state: {

        lng:lng,// 经度

        lat:lat,// 纬度

      },

      mutations: {

        changelng(state, e) {

          state.lng = e

          try {

            localStorage.lng = e

          } catch (e) {}

        },

        changelat(state, e) {

          state.lat = e

          try {

            localStorage.lat = e

          } catch (e) {}

        },

      }

    })

     

  • 相关阅读:
    linux系统--磁盘管理命令(二)
    linux系统--磁盘管理命令(一)
    linux系统--用户和用户组
    linux4.10.8 内核移植(四)---字符设备驱动_led驱动程序
    linux4.10.8 内核移植(三)---裁剪内核
    linux4.10.8 内核移植(二)---初步裁剪、分区修改和文件系统
    Linux 4.10.8 根文件系统制作(三)---制作yaffs文件系统
    Kotlin的面向对象入门
    Python 中的GIL
    python 虚拟环境的 安装与 使用 和修改为豆瓣源
  • 原文地址:https://www.cnblogs.com/suisuisui/p/9771149.html
Copyright © 2011-2022 走看看