【vuex】安装和使用 and 解决vuex的state刷新之后变为原来数值的问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dangbai01_/article/details/84027151

Pre:安装

npm install vuex -S

1.首先我们创建一个store文件夹,然后我们在文件夹中放一个store.js

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({

  state:{

扫描二维码关注公众号,回复: 4081502 查看本文章

    login:"isNoLogin"

  },

  mutations:{

    loginchange:(state,qcLogin)=> {

        //应对界面刷新,数据会刷新为最原本的login,所以我们在这里进行一下存储

        state.login = qcLogin

        window.localStorage.setItem('qcLogin', state.login);

    },

  }

})

2.然后在main .js  中导入

import Vue from 'vue'

import App from './App'

import store from './store/store'

/* eslint-disable no-new */

new Vue({

  el: '#app',

  store,

  components: { App },

  template: '<App/>'

})

3.在组件中使用(这里用的是element-ui,有兴趣的话可以了解一下)

template

        <el-col :span="3" align="center">

          <div class="grid-content bg-purple-light">

            <el-button icon="el-icon-view" @click="vuexClick">{{vuex}}</el-button>

          </div>

        </el-col>

<script>

    import { mapState } from 'vuex'

    export default {

      name: 'App’,

      data(){

        return{

          //创建一个localData,用来接收存储的数据

          localData:'',

        }

      },

      created(){

        //如果已经存了,就会存储下来,我们在这里直接接收一下

        this.localData = window.localStorage.getItem('qcLogin')

        console.log(this.localData)

      },

      /*

         computed是在HTML DOM加载后马上执行的,如赋值;

      */

      computed: {

         //将store.login映射了this.login

         ...mapState([

             'login'

         ]),

         vuex(){

             //如果之前commit过mutation,直接使用变化之后的值,如果没有就是用store.login

             return  this.localData.length >0 ? this.localData:this.login

         }

      },

     methods:{

      //测试vuex

      vuexClick(){

        this.$store.commit("loginchange",'isLogin')

        //重新输出

        console.log(this.localData)

      },

}

</script>

猜你喜欢

转载自blog.csdn.net/dangbai01_/article/details/84027151
今日推荐