视频电商网站 - vuex多个module交互
我们的项目使用了Vuex,关于Vuex是什么看这里:http://vuex.vuejs.org/zh-cn/intro.htmlVuex里有个Modules的概念:http://vuex.vuejs.org/zh-cn/modules.html我们前面用户登录获取access_token等信息,都是写在UsersModule.js这个module中的。http://blog.csdn.n
我们的项目使用了Vuex
,关于Vuex
是什么看这里:
http://vuex.vuejs.org/zh-cn/intro.html
Vuex里有个Modules
的概念:
http://vuex.vuejs.org/zh-cn/modules.html
我们前面用户登录获取access_token等信息,都是写在UsersModule.js
这个module中的。
http://blog.csdn.net/github_26672553/article/details/70048077
Vuex多个module交互
我们的项目使用了Vuex
,关于Vuex
是什么看这里:
http://vuex.vuejs.org/zh-cn/intro.html
Vuex里有个Modules
的概念:
http://vuex.vuejs.org/zh-cn/modules.html
现在假如我们有一个VideosModule.js
专门用来处理我们视频模块(视频列表展示)
actions:{
loadVideos(context,params){
axios.get("localhost://xxxx/load-video.php?access-token").then(function(res){
console.log(res.data);
})
}
}
在这个地方,我们需要给access-token
赋值,需要获取保存在客户端的值了。
我们之前已经在UsersModules.js
里写好了:
state:{
currentUser:{
get UserName(){
let username = localStorage.getItem("currentUser_name");
if (username==null || username== undefined){
return "guest";
}
return username;
},
get UserToken(){
return localStorage.getItem("currentUser_token");
}
}
},
通过currentUser
就可以获取到。
但是现在我们是在VideosModule.js
里,我们又怎么样获取该数据呢?
可以通过context.rootState.users.currentUser
来获取。
users
是我们在入口文件member-index.js
给Vuex配置modules的名称。
其他:
一般来说不要把我们的业务代码放到modules里面,比如登录
loadVideos(context,params){
if(content.rootStae.users.currentUser.username == "guest"){
//去登录
Vue.prototype.function.needLogin();
}
}
我们加载视频的时候如果用户没有登录,就去登录页。
needLogin()
函数哪来的?
fucction.js中定义的:
export default{
getVersion(){
return '1.0';
},
needLogin(){
self.location = "users/login";
}
}
那又为何可全局调用呢?
这个就要看vue的插件知识了:
http://cn.vuejs.org/v2/guide/plugins.html
我们这里有一个global.js
就是一个插件,代码如下:
import functions from './function';
import APIConfig from './../config/APIConfig';
export default{
//Vue开发插件必须有的方法
//参考文档:http://cn.vuejs.org/v2/guide/plugins.html
install(Vue){
Vue.prototype.functions = functions;
Vue.prototype.APIConfig = APIConfig;
}
}
可以看到,在install
方法里设置了Vue.prototype.functions = functions
。
最后在入口文件中引入并使用这个插件就好了:
import global from './global'; //我们自己写的全局插件
Vue.use(global);
更多推荐
所有评论(0)