码迷,mamicode.com
首页 > 其他好文 > 详细

vuex配置

时间:2020-03-25 12:03:17      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:ora   ons   comm   this   component   state   new   als   vuex   

例:在src下面新建一个文件夹store,在store里新建文件夹modules和index.js,在modules里新建文件token.js,在token.js里做登录拦截

 

token.js

export default {
    state: {
        token: null,
        title:‘‘
    },
    mutations: {
        login(state, data) {
            // console.log(‘login‘)
            localStorage.token = data;
            state.token = data;
        },
        logout(state) {
            // console.log(‘logout‘)
            localStorage.removeItem(‘token‘);
            state.token = null
        },
        title(state,txt){
            state.title = txt
        }
    },
    getters: {
        getToken: state => state.token
    },
    actions: {
        newTitle({commit},data){
            commit(‘title‘,titHandle(data))
        }
    }
}

function titHandle(data){
    let txt = ‘state.token.token,state.token中的token为在store.js中引入modules的自定义名字,‘
    return txt + data
}

store文件夹下的index.js

import Vuex from ‘vuex‘
import Vue from ‘vue‘

Vue.use(Vuex);

import token from ‘./modules/token‘

export default new Vuex.Store({
    modules: {
        token
    }
})

在main.js里引入store

import Vue from ‘vue‘
import App from ‘./App‘
import router from ‘./router‘


import store from ‘./store‘

/* eslint-disable no-new */
new Vue({
  el: ‘#app‘,
  router,

  store,
  
  components: { App },
  template: ‘<App/>‘
})

页面引用

<script>
    import {mapState,mapGetters,mapActions} from ‘vuex‘
    export default {
        computed: {
            ...mapState({
                tokenState: state => state.token.token
            }),
            ...mapGetters([
                ‘getToken‘
            ])
        },
        created(){
            console.log(this.tokenState);
            // 调用Actions方法
            this.newTitle()
        },
        methods: {
            ...mapActions({
                ‘newTitle‘:‘newTitle‘
            }),
        }
    }
</script>

 

vuex配置

标签:ora   ons   comm   this   component   state   new   als   vuex   

原文地址:https://www.cnblogs.com/lijh03/p/12565100.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!