美文网首页
vue vue-router vuex element-ui a

vue vue-router vuex element-ui a

作者: 思吾谓何思 | 来源:发表于2017-11-13 21:00 被阅读0次
    Image 121.png

    经过我不懈的思考和实验终于找到了该如何用vuex管理登录状态,效果还可以,虽然在大佬眼里可能知识小儿科
    首先store.js这样写就可以了

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    // 创建基本状态
    const state = {
      user: JSON.parse(sessionStorage.getItem('user')) || ''
    }
    // 创建改变状态的方法
    const mutations = {
      // 登录
      LOGIN (state) {
        state.user = JSON.parse(sessionStorage.getItem('user'))
      },
      // 登出
      LOGOUT (state) {
        state.user = ''
      }
    }
    // 创建驱动actions可以使得mutations得以启动
    const actions = {
      // 这里先来一个驱动LOGIN的东西就叫login吧
      login ({commit}) {
        commit('LOGIN')
      },
      // 同样来个logout
      logout ({commit}) {
        commit('LOGOUT')
      }
    }
    
    export default new Vuex.Store({
      state,
      mutations,
      actions
    })
    
    

    这样写可以把sessionStorage里面整个user都直接放在store里面,用户密码在返回数据的时候已经强制写成了null,做到这里真想给自己一浪锤,开始做的时候怎么就没想到这样写了?真的是实践出真知啊。

    因为已经把action的diapatch写好了,只需要从store读数据就可以了
    header.vue
    读数据


    Image 122.png

    使用数据


    Image 123.png

    my.vue


    Image 124.png

    测试:
    先登录

    Image 125.png
    提示登录成功,右上角和mydata都显示出了该有的数据
    测试退出登录
    Image 126.png
    Image 127.png
    提示退出成功,右上角也显示出了登录和注册按钮
    测试刷新页面
    在登录一次
    Image 128.png
    刷新
    Image 129.png
    刷新是正常的,仍然可以正确获取状态,虽然从图上看不出来。

    总结一下:vuex折腾了几天,也许算勉强入门了吧,按官方的要求应该是写成点击提交之后所有异步操作都写在actions里面,包含发送axios请求这些,然后把登录、注册、登出的state,mutation,actions都写在一个module里面,方便管理,我现在还没这么深入,继续写下去如商品管理,发货管理可以会这么用到,到时候再深入研究一下。



    顺便再把footer页面写一下,这样至少看起来像一个完整的页面了
    footer.vue
    <template>
    <el-row  class="footer">
      <el-col :span="8">
        <img src="../assets/logo.png" alt="">
      </el-col>
      <el-col :span="16">
        <p class="copy">Copyright © 2015-2017.会理县未济网络科技有限公司.All Rights Reserved.</p>
        <p class="beian">ICP备案号:蜀ICP备17008055号</p>
      </el-col>
    </el-row>
    
    </template>
    <style scoped>
    .footer {
      background: #eee;
    }
    img {
      width: 80px;
      height: 80px;
      margin: 40px 0;
    }
    p {
      margin: 50px 10px;
      color: #666;
    }
    </style>
    
    

    随便写下,还是看起来丑,犯这个就是个意思


    Image 130.png

    明天开始写商品页面

    相关文章

      网友评论

          本文标题:vue vue-router vuex element-ui a

          本文链接:https://www.haomeiwen.com/subject/dwazmxtx.html