vuex在单独js文件调用显示commit is not a function
最近做的vue项目需要存储登录信息,上网搜了一下说要用到vuex,于是按照网上教程操作
先是npm install vuex --save 安装vuex包
然后创建store文件夹,并在里面添加store.js文件
在store.js里输入
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = { //存储登录信息
userName:'xixi',
tpye:0,
shcoolNumber:"",
valid:1
}
const getters ={
currentUser(){
return state.userName;
},
userTpye(){
return state.tpye;
}
}
const mutations = { //修改state内容的方法写在这,在外部通过commit(‘方法名’,参数)调用
setUser(state,username,tpye1,shcoolnumber,valid1){
state.userName=username;
state.tpye=tpye1;
state.shcoolNumber=shcoolnumber;
state.valid=valid1;
}
}
export default new Vuex.Store({ //别忘把const的内容导出
state,
getters,
mutations,
})
记住在main.js里注册全局
import iView from 'iview';
import 'iview/dist/styles/iview.css';
import store from './store/store';
Vue.config.productionTip = false
Vue.use(iView);
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store, //注册store
components: { App },
template: '<App/>',
})
然后就可以在组件里通过$store.state.userName或者$store.currentUser获取,通过$store.commit()调用mutations里的方法。
在单独js文件里调用
但由于之前写angular项目的习惯,把接口都写在单独js里,调用的时候出了点问题。
这是user.js
首先,在第三行引入store.js,但是运行时会报错,store.commit is not a function,输出store发现是有commit方法的
但是store的方法都在default下,于是改成下面
便能正常使用了