在Mvc模式大行其道的今天,後端經過各類Mvc框架實現視圖與數據模型的隔離,而前端這方面也發展迅速。vue實現了Dom與viewModel雙向綁定,使其視圖的更新影響模型,模型的更新影響視圖,你會不會以爲這就是Mvc庫呢,實則否則,由於他還差一個重要的C(也就是控制器)。如下是鄙人對Mvc的我的理解,若有失誤還請各位道友指正。css
這個重要的C是誰呢,鄙人認爲就是此文章要介紹的Vuex(若是你想初識vue,能夠移步vue原來能夠這樣上手這篇博文)。如此理解也是能夠的:vue + vuex = 前端mvc框架html
本示例實現爲一個輸入框動態向下拉列表增長選擇項的功能源碼下載地址,先看效果圖:前端
爲了展現vuex的做用,此示例你能夠看到以下內容:vue
//Vue.use(Vuex);//若是是window引入方式,vuex會自動附加到Vue上。 var state = { list: [{"id":1, "name": "001"}] }; var mutations = { ADDITEM: function(argState, item){ argState.list.push(item); } }; var getters = { getList:function(argState){ return argState.list; } } var actions = { addItem:function(dis,item){ dis.commit('ADDITEM',item); } } var _storeObj = new Vuex.Store({ "state": state, "mutations": mutations, "getters": getters, "actions": actions });
vuex更新數據流程:jquery
var inputComp = { render:function(createElement){ var self = this; return createElement('div',{ attrs:{ "data-id": "001" }, class:{ "form-inline":true }, style:{ "display": "inline-block" } },[createElement('input',{ attrs:{ type: 'text' }, class:{ "form-control": true }, domProps:{ value: self.value }, on:{ input:function(event){ self.value = event.target.value; } } }),createElement('button',{ on:{ "click": function(event){ self.$store.dispatch('addItem',{"id":2,"name": self.value}); } }, class:{ "btn":true, "btn-primary": true }, domProps:{ type: 'button' } },"添加")]); } }; //下拉列表組件 var ComboComp = { render:function(createElement){ var self = this; return createElement("div",{ attrs:{ "data-id": "ComboComp" }, class:{ "dropdown":true }, style:{ "display": "inline-block" } },[ createElement("button",{ class:{ "btn": true, "btn-default": true, "dropdown-toggle": true }, attrs:{ "type": "button", "id": "dr02", "data-toggle": "dropdown" } },[ createElement("span", "選擇"), createElement("span",{ class:{ "caret":true } })]) , createElement("ul", { class:{ "dropdown-menu":true }, attrs:{ "aria-labelledby":"dr02" } }, self.$store.getters["getList"].map(function(item){ return createElement("li",item.name); })) ]) } }; Vue.component('App',{ template:'<div class="wrap" ><ComboComp></ComboComp> <InputComp></InputComp></div>', components:{ "InputComp": inputComp, "ComboComp": ComboComp } });
createElement('button',{ on:{ "click": function(event){ self.$store.dispatch('addItem',{"id":2,"name": self.value}); } }
html部分代碼:vuex
<div class="wrap" id="app"> <App></App> </div>
js部分代碼:redux
var _vue = new Vue({ el: '#app', store: _storeObj });