Vuex速学篇:(4)把我们的业务按模块分类
文档:http://vuex.vuejs.org/zh-cn/modules.html
这个modules是用来干什么的?
前面我们做了一个这样的界面,有登录,有热点新闻。
我们学到了vuex
这样一个框架。
我们可以看到state
里,我们把user_name和新闻是糅合在一起的,如果我们这个项目的多人协作开发,这样就不是很方便。
所以modules
就起到了这样一个作用。
我们来演示一下怎么使用这个modules
1.项目结构(我们参考了官方的http://vuex.vuejs.org/zh-cn/structure.html)
把用户和新闻模块分开。
2.UserModules.js:
export default{
state:{
user_name:""
},
mutations:{
showUserName(state){
alert(state.user_name);
}
},
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
3.NewsModules.js:
export default{
state:{
newslist:[],
newsdetail:{}
},
mutations:{
setAgree(state,agreeNum){
state.newsdetail.agree = agreeNum;
}
},
actions:{
agree(context,newsid){
// 进行请求,获取点赞后的agree字段属性值
Vue.http.post("http://localhost/agree.php",{newsid:newsid},{emulateJSON:true}).then(function (res) { // 处理业务 // 调用上面setAgree方法更新点赞数 context.commit("setAgree",res.body.agree); },function(){}) } }, getters:{ getNews(state){ return state.newslist.filter(function (news) { return !news.isdeleted; }) } } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
4.这2步做好之后,我们已经把用户和新闻分离了,分离之后怎么引入呢?
import UserModule from "./../store/modules/UserModule";
import NewsModule from "./../store/modules/NewsModule";
- 1
- 2
const vuex_store = new Vuex.Store({
modules:{
users:UserModule,
news:NewsModule
}
})
- 1
- 2
- 3
- 4
- 5
- 6
这个时候是否大功告成呢,肯定不是
5.之后我们需要修改组件 news-list.vue
:
需要修改此处的代码,需要加上我们的模块名,修改之后:
<script>
export default{
created(){
if (this.$store.state.news.newslist.length == 0){ // 请求服务器获取数据 this.$http.get("http://localhost/news.php").then(function (res) { this.$store.state.news.newslist = res.body; },function (res) { // 请求失败处理 }) } } } </script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
this.$store.state.news.newslist
,news
就是前面定义的module名。
user-name.vue
:
如果我们不做任何修改,点击“提交”按钮是获取不到用户输入的用户名的
修改如下:
<script>
export default{
props:["placeholder"], data:function () { return { username:"" } }, methods:{ userNameChange(){ //this.$emit("childChange","username",this.username) this.$store.state.users.user_name = this.username; } } } </script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
this.$store.state.user_nam
修改为:this.$store.state.users.user_name
。
至此,聪明的你应该已经发现:之前代码所有用到state
的地方,都应该加上module名称来访问。
其他注意点
// 进行请求,获取点赞后的agree字段属性值
Vue.http.post("http://localhost/agree.php",{newsid:newsid},{emulateJSON:true}).then(function (res) { // 处理业务 // 调用上面setAgree方法更新点赞数 context.commit("setAgree",res.body.agree); },function(){})
NewsModule.js中,我们是通过Vue.http.post()
来获取服务器数据的,可能会找不到Vue
,所以在这个文件头部,我们再次引入一下:
import Vue from "vue";