在Mvc模式大行其道的今天,后端通過各種Mvc框架實現視圖與數據模型的隔離,而前端這方面也發展迅速。vue實現了Dom與viewModel雙向綁定,使其視圖的更新影響模型,模型的更新影響視圖,你會不會覺得這就是Mvc庫呢,實則不然,因為他還差一個重要的C(也就是控制器)。以下是鄙人對Mvc的個人理解,如有失誤還請各位道友指正。
第一部分:我對vuex的理解
這個重要的C是誰呢,鄙人認為就是此文章要介紹的Vuex。如此理解也是可以的:vue + vuex = 前端mvc框架
flux(單向數據流)
vuex是借鑒了flux、redux、The Elm Architecture等相關思想。
第二部分:揭開vuex面紗
本示例實現為一個輸入框動態向下拉列表增加選擇項的功能源碼下載地址,先看效果圖:

為了展示vuex的作用,此示例你可以看到如下內容:
一、實現vuex的store實例
//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更新數據流程:

二、實現vue的組件
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 }});1.inputComp(局部組件):提供輸入
2.ComboComp(局部組件):實現列表內容的展示
3.App(全局組件):頂級組件,組合inputComp和ComboComp組件。
4.組件參數說明:
render:返回一個組件,其中包含視圖,data等。this為vue實例,參數是createElement方法,用于創建VNode。
5.重點關注inputComp組件中button子元素的on中的click方法,內部用dispatch觸發了store中對應Id的actions。
createElement('button',{on:{ "click": function(event){ self.$store.dispatch('addItem',{"id":2,"name": self.value}); }}三、輸出
html部分代碼:
<div class="wrap" id="app"> <App></App></div>
js部分代碼:
var _vue = new Vue({ el: '#app', store: _storeObj});以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網!
新聞熱點
疑難解答