文檔:http://vuex.vuejs.org/zh-cn/modules.html
這個(gè)modules是用來(lái)干什么的?
這樣一個(gè)框架。
里,我們把user_name和新聞是糅合在一起的,如果我們這個(gè)項(xiàng)目的多人協(xié)作開發(fā),這樣就不是很方便。 所以modules
就起到了這樣一個(gè)作用。
我們來(lái)演示一下怎么使用這個(gè)modules
1.項(xiàng)目結(jié)構(gòu)(我們參考了官方的http://vuex.vuejs.org/zh-cn/structure.html) 把用戶和新聞模塊分開。
export default{ state:{ user_name:"" }, mutations:{ showUserName(state){ alert(state.user_name); } },}
3.NewsModules.js:
export default{ state:{ newslist:[], newsdetail:{} }, mutations:{ setAgree(state,agreeNum){ state.newsdetail.agree = agreeNum; } }, actions:{ agree(context,newsid){ // 進(jìn)行請(qǐng)求,獲取點(diǎn)贊后的agree字段屬性值 Vue.http.post("http://localhost/agree.php",{newsid:newsid},{emulateJSON:true}).then(function (res) { // 處理業(yè)務(wù) // 調(diào)用上面setAgree方法更新點(diǎn)贊數(shù) context.commit("setAgree",res.body.agree); },function(){}) } }, getters:{ getNews(state){ return state.newslist.filter(function (news) { return !news.isdeleted; }) } }}
4.這2步做好之后,我們已經(jīng)把用戶和新聞分離了,分離之后怎么引入呢?
import UserModule from "./../store/modules/UserModule";import NewsModule from "./../store/modules/NewsModule";
const vuex_store = new Vuex.Store({ modules:{ users:UserModule, news:NewsModule }})
這個(gè)時(shí)候是否大功告成呢,肯定不是
:
<script> export default{ created(){ if (this.$store.state.news.newslist.length == 0){ // 請(qǐng)求服務(wù)器獲取數(shù)據(jù) this.$http.get("http://localhost/news.php").then(function (res) { this.$store.state.news.newslist = res.body; },function (res) { // 請(qǐng)求失敗處理 }) } } }</script>
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>
this.$store.state.user_nam
修改為:this.$store.state.users.user_name
。
至此,聰明的你應(yīng)該已經(jīng)發(fā)現(xiàn):之前代碼所有用到state
的地方,都應(yīng)該加上module名稱來(lái)訪問(wèn)。
其他注意點(diǎn)
// 進(jìn)行請(qǐng)求,獲取點(diǎn)贊后的agree字段屬性值Vue.http.post("http://localhost/agree.php",{newsid:newsid},{emulateJSON:true}).then(function (res) {// 處理業(yè)務(wù)// 調(diào)用上面setAgree方法更新點(diǎn)贊數(shù)context.commit("setAgree",res.body.agree);},function(){})
NewsModule.js中,我們是通過(guò)Vue.http.post()
來(lái)獲取服務(wù)器數(shù)據(jù)的,可能會(huì)找不到Vue
,所以在這個(gè)文件頭部,我們?cè)俅我胍幌拢?br>
import Vue from "vue";