• 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) {}

        },

      }

    })

     

  • 相关阅读:
    xcode构建webdriverAgent时报错Messaging unqualified id的解决办法
    ubuntu18.0安装RabbitMQ
    python中*的用法
    Jenkins构建项目
    Jenkins安装与配置
    git_仓库
    六、 Shell数组应用
    五、 Shell函数应用
    三、 Shell流程控制
    二、 Shell变量定义
  • 原文地址:https://www.cnblogs.com/suisuisui/p/9771149.html
Copyright © 2020-2023  润新知