vuex+axios+es6+vue-router+elementui管理系統(tǒng)實(shí)踐

創(chuàng)建項(xiàng)目


vue create vuextest2

cd vuextest2

yarn serve

  • 安裝vuex ,vue-router, element-ui

// 安裝 vuex

npm install vuex --save

//或

yarn add vuex

//安裝vue-router

npm install --save vue-router

//安裝element-ui

npm i element-ui -S

  • 在src下創(chuàng)建router文件夾router/index.js

import Vue from "vue";

import Router from "vue-router";

// 引入組件

import Login from "@/components/login";

//注冊組件

Vue.use(Router);

//導(dǎo)出組件

export default new Router({

  routes: [

    {

      path: "/",

      name: "login",

      component: Login

    }

  ],

  mode: "history" //去除地址欄中的#號

});

  • main.js中引入路由

import router from "./router";

Vue.config.productionTip = false;

new Vue({

  router,

  render: h => h(App)

}).$mount("#app");

  • 引入 Element

//在 main.js 中添加以下內(nèi)容:

import ElementUI from 'element-ui'

import 'element-ui/lib/theme-chalk/index.css'

Vue.use(ElementUI)

  • 引入重置樣式reset.css

在src下新建css/reset.css文件網(wǎng)上下載reset.css樣式,

在index.html中:


<link rel="stylesheet" href="../src/static/css/reset.css">

vue中的節(jié)點(diǎn)操作ref和this.$refs.名稱


<div id="app">

    <input type="text" ref="input1" class="input1"/>

    <button @click="add">添加</button>

</div>

<script>

new Vue({

    el: "#app",

    methods:{

        add:function(){

          this.$refs.input1.value ="22"; //this.$refs.input1  減少獲取dom節(jié)點(diǎn)的消耗

        }

    }

})

</script>

一般來講,獲取DOM元素筑悴,需document.querySelector(".input1")獲取這個dom節(jié)點(diǎn),然后在獲取input1的值较鼓。

但是用ref綁定之后立倍,我們就不需要在獲取dom節(jié)點(diǎn)了舍哄,直接在上面的input上綁定input1溪椎,然后$refs里面調(diào)用就行普舆。

然后在javascript里面這樣調(diào)用:this.$refs.input1 這樣就可以減少獲取dom節(jié)點(diǎn)的消耗了。

前后端數(shù)據(jù)交互--axios

  • 安裝axios

npm i -S axios

  • 在main.js中

// 引入axios

import axios from "axios";

// 掛載在vue的原型上校读,這樣每個vue實(shí)例都可以使用這個方法

Vue.prototype.axios = axios;

用node.js啟動一個后端服務(wù)接口


//全局安裝express

npm install express -g

npm install -g express-generator

//創(chuàng)建服務(wù)項(xiàng)目

express server -e

// 初始化項(xiàng)目

cd server

npm install

//啟動服務(wù)器

nodemon app

解決跨域問題 --- 配置代理

創(chuàng)建vue.config.js文件


module.exports = {

  devServer: {

  proxy: {

    '/api': {

      target: 'http://localhost:888',

      ws: true,

      changeOrigin: true,

      pathRewrite: {

        '^/api': ''  //通過pathRewrite重寫地址,將前綴/api轉(zhuǎn)為/

      }

    }

  }

}

//在頁面發(fā)起請求:

axios.get('/api/address').then(res => {

  console.log(res)

})

此處改為請求https://jsonplaceholder.typicode.com/users接口數(shù)據(jù)

登錄成功后請求到數(shù)據(jù)祖能,利用vuex存儲數(shù)據(jù)

創(chuàng)建index.vue后臺頁面,然后配置路由

vue組件異步加載

  1. 使用() => import()

const ImportFuncDemo1 = () => import('../components/ImportFuncDemo1')

  1. 使用resolve => require(['./_account'], resolve)
  1. 使用Webpack 的內(nèi)置語句: import(*)

vuex數(shù)據(jù)處理

  • 安裝

npm i vuex -S

創(chuàng)建store/store.js文件


import Vue from "vue";

import Vuex from "vuex";

Vue.use(Vuex);

const state = {

  userInfo: {}

};

const mutations = {

  SAVE_USERINFO(state, userInfo) {

    state.userInfo = userInfo;

  }

};

export default new Vuex.Store({

  state,

  mutations

});

在main.js中引入store


import store from "./store/store";

new Vue({

  router,

  store,

  render: h => h(App)

}).$mount("#app");

一般在組件中觸發(fā)mutations


// login.vue中

_this.$store.commit("SAVE_USERINFO",response.data[0])

在刷新頁面后要確保數(shù)據(jù)依然存在,則需要在拿到數(shù)據(jù)后將其存入本地存儲


localStorage.setItem('userInfo',JSON.stringify(response.data[0]));

上面做法任然會在刷新后數(shù)據(jù)沒有歉秫,采取以下做法:直接將數(shù)據(jù)提交到store的state中,然后在mutations 中先將數(shù)據(jù)存到本地存儲养铸,然后再更新數(shù)據(jù).


const state = {

  userInfo: JSON.parse(localStorage.getItem("userInfo"))

};

const mutations = {

  SAVE_USERINFO(state, userInfo) {

    // 先將數(shù)據(jù)存到本地存儲

    localStorage.setItem("userInfo", JSON.stringify(userInfo));

    state.userInfo = userInfo;

  }

};

在組件中獲取state有兩種方式(home.vue)

第一種在組件中直接拿


<span>{{$store.state.userInfo.username}}</span>

第二種通過計(jì)算屬性computed獲取store的數(shù)據(jù)


computed: {

    username() {

      return this.$store.state.userInfo.username;

    }

  }

  • mapState輔助函數(shù)(推薦使用)

import {mapState} from "vuex";

computed:{

  ...mapState({

    userinfo:state => state.userInfo;

  })

}

actions處理異步操作


// store.js

// 1. 在state中添加userList存儲用戶列表的數(shù)據(jù)

const state = {

  userInfo: JSON.parse(localStorage.getItem("userInfo")),

  userList: []

};

// 2. 在mutations中添加獲取用戶列表的函數(shù)

const mutations = {

  GET_USERLIST(state,userlist){

    state.userList = userlist;

  }

}

// 定義actions,異步的雁芙,主要是用來commit mutations,再有mutations來改變狀態(tài)state

const actions = {

  GET_USERLIST({ commit }) {

    return new Promise((resolve, reject) => {

      // 此處的請求為異步操作 為了能拿到數(shù)據(jù)钞螟,就在外面包一層promise

      axios.get("https://jsonplaceholder.typicode.com/users").then(res => {

        //   console.log("獲取用戶數(shù)據(jù)", res.data);

        commit("GET_USERLIST", res.data);

        resolve();

      });

    });

  }

};

//main.js觸發(fā)actions測試數(shù)據(jù)獲取

store.dispatch("GET_USERLIST").then(() => {

  console.log("獲取數(shù)據(jù):", store.state.userList);

});

在用戶列表組件里兔甘,可在生命周期鉤子函數(shù)里去獲取數(shù)據(jù)


// userlist.vue

created(){

  this.$store.dispatch("GET_USERLIST").then(()=>{

    const data = this.$store.state.userList;

    this.tableData = data;

  })

}

可以用輔助函數(shù)來簡化操作:


import {mapState,mapActions} from "vuex";

// mapState

created() {

  this.$store.dispatch("GET_USERLIST").then(() => {

    //   const data = this.$store.state.userList;

    //   this.tableData = data;

    this.tableData = this.userList;

  });

},

computed:{

  // ...mapState(["userList"])

  ...mapState({

    userList:state => state.userList;

  })

}


//mapActions

created(){

  this.GET_USERLIST().then(() => {

    this.tableData = this.userList;

  })

},

methods:{

  ...mapActions(["GET_USERLIST"]);

}

Getter

有時候我們需要從 store 中的 state 中派生出一些狀態(tài),例如對列表進(jìn)行過濾并計(jì)數(shù).

Vuex在store中定義的getters可以認(rèn)為是store的計(jì)算屬性鳞滨,getters的返回值會根據(jù)它的依賴被緩存起來洞焙,且只有當(dāng)它的以來至發(fā)生改變才會被重新計(jì)算。

Getter接受state作為第一個參數(shù)拯啦,Getter會暴露為store.getters對象澡匪,你可以以屬性的形式訪問這些值。

你也可以通過讓 getter 返回一個函數(shù)褒链,來實(shí)現(xiàn)給 getter 傳參唁情。在你對 store 里的數(shù)組進(jìn)行查詢時非常有用。


getters:{

  getTodoById:(state) => (id) => {

    return state.todos.find(todo => todo.id === id);

  }

}

注意甫匹,getter 在通過方法訪問時甸鸟,每次都會去進(jìn)行調(diào)用,而不會緩存結(jié)果兵迅。

輔助函數(shù)mapGetters

mapGetters 輔助函數(shù)僅僅是將store中的getter映射到局部計(jì)算屬性:

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末抢韭,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子喷兼,更是在濱河造成了極大的恐慌篮绰,老刑警劉巖,帶你破解...
    沈念sama閱讀 223,126評論 6 520
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件季惯,死亡現(xiàn)場離奇詭異吠各,居然都是意外死亡臀突,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,421評論 3 400
  • 文/潘曉璐 我一進(jìn)店門贾漏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來候学,“玉大人,你說我怎么就攤上這事纵散∈崧耄” “怎么了?”我有些...
    開封第一講書人閱讀 169,941評論 0 366
  • 文/不壞的土叔 我叫張陵伍掀,是天一觀的道長掰茶。 經(jīng)常有香客問我,道長蜜笤,這世上最難降的妖魔是什么濒蒋? 我笑而不...
    開封第一講書人閱讀 60,294評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮把兔,結(jié)果婚禮上沪伙,老公的妹妹穿的比我還像新娘。我一直安慰自己县好,他們只是感情好围橡,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,295評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著缕贡,像睡著了一般翁授。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上善绎,一...
    開封第一講書人閱讀 52,874評論 1 314
  • 那天黔漂,我揣著相機(jī)與錄音,去河邊找鬼禀酱。 笑死炬守,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的剂跟。 我是一名探鬼主播减途,決...
    沈念sama閱讀 41,285評論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼曹洽!你這毒婦竟也來了鳍置?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,249評論 0 277
  • 序言:老撾萬榮一對情侶失蹤送淆,失蹤者是張志新(化名)和其女友劉穎税产,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,760評論 1 321
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡辟拷,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,840評論 3 343
  • 正文 我和宋清朗相戀三年撞羽,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片衫冻。...
    茶點(diǎn)故事閱讀 40,973評論 1 354
  • 序言:一個原本活蹦亂跳的男人離奇死亡诀紊,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出隅俘,到底是詐尸還是另有隱情邻奠,我是刑警寧澤,帶...
    沈念sama閱讀 36,631評論 5 351
  • 正文 年R本政府宣布为居,位于F島的核電站碌宴,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏颜骤。R本人自食惡果不足惜唧喉,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,315評論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望忍抽。 院中可真熱鬧,春花似錦董朝、人聲如沸鸠项。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,797評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽祟绊。三九已至,卻和暖如春哥捕,著一層夾襖步出監(jiān)牢的瞬間牧抽,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,926評論 1 275
  • 我被黑心中介騙來泰國打工遥赚, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留扬舒,地道東北人。 一個月前我還...
    沈念sama閱讀 49,431評論 3 379
  • 正文 我出身青樓凫佛,卻偏偏與公主長得像讲坎,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子愧薛,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,982評論 2 361

推薦閱讀更多精彩內(nèi)容