vuex配置
Posted lijh03
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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配置的主要内容,如果未能解决你的问题,请参考以下文章