Vuex2.0+Vue2.0構建備忘錄應用實踐

1、介紹Vuex

Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式。它採用集中式存儲管理應用的全部組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化,適合於構建中大型單頁應用。css

一、什麼是狀態管理模式?

看個簡單的例子:html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Vuex Demo 01</title>
<script src="http://cdn.bootcss.com/vue/1.0.26/vue.min.js"></script>
<script src="http://cdn.bootcss.com/vuex/0.8.2/vuex.min.js"></script>
</head>
<body>
  <!-- 二、view,映射到視圖的數據counterValue; -->
  <h3>Count is {{ counterValue }}</h3>
  <div>
    <button @click="increment">Increment +1</button>
    <button @click="decrement">Decrement -1</button>
  </div>
</body>
<script>
var app = new Vue({
  el: 'body',
  store: new Vuex.Store({
    // 一、state,驅動應用的數據源;
    state: {
      count: 0
    },
    mutations: {
      INCREMENT: function(state, amount) {
        state.count = state.count + amount
      },
      DECREMENT: function(state, amount) {
        state.count = state.count - amount
      }
    }
  }),
  vuex: {
    getters: {
      counterValue: function(state) {
        return state.count
      }
    },
    // 三、actions,響應在view上的用戶輸入致使的狀態變化。
    actions: {
      increment: function({ dispatch, state }){
        dispatch('INCREMENT', 1)
      },
      decrement: function({ dispatch, state }){
        dispatch('DECREMENT', 1)
      }
    }
  }
})
</script>
</html>

代碼中標識了:vue

一、state,驅動應用的數據源;
二、view,映射到視圖的數據counterValue;
三、actions,響應在view上的用戶輸入致使的狀態變化。

用簡單示意圖表示他們之間的關係:webpack

咱們知道,中大型的應用通常會遇到多個組件共享同一狀態的狀況:git

一、多個視圖依賴於同一狀態es6

二、來自不一樣視圖的行爲須要變動同一狀態github

因而須要把組件的共享狀態抽取出來,以一個全局單例模式管理,另外,須要定義和隔離狀態管理中的各類概念並強制遵照必定的規則。web

這就是 Vuex 背後的基本思想,借鑑了 FluxRedux、和 The Elm Architecture。與其餘模式不一樣的是,Vuex 是專門爲 Vue.js 設計的狀態管理庫,以利用 Vue.js 的細粒度數據響應機制來進行高效的狀態更新。vue-router

二、Vuex的核心概念

一、State: 單一狀態樹,用一個對象包含了所有的應用層級狀態,做爲一個『惟一數據源(SSOT)』而存在,每一個應用將僅僅包含一個 store 實例。vuex

二、Getters: Vuex 容許咱們在 store 中定義『getters』(能夠認爲是 store 的計算屬性)。

三、Mutations: Vuex 中的 mutations 很是相似於事件:每一個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調函數 (handler)。這個回調函數就是咱們實際進行狀態更改的地方,而且它會接受 state 做爲第一個參數。

四、Actions: 相似於 mutation,不一樣在於:①Action 提交的是 mutation,而不是直接變動狀態;②Action 能夠包含任意異步操做。

五、Modules: 爲解決單一狀態樹致使應用的全部狀態集中在一個store對象的臃腫問題,Vuex將store分割到模塊(module)。每一個模塊擁有本身的 state、mutation、action、getters、甚至是嵌套子模塊——從上至下進行相似的分割。

接着咱們開始構建備忘錄應用,在如下構建過程的介紹中,再加深理解上述概念。

2、環境安裝

1.安裝 vue-cli

2.初始化應用

vue init webpack vue-notes-demo
cd vue-notes-demo
npm install // 安裝依賴包
npm run dev // 啓動服務

結果爲:

目錄結構爲:

3、功能模塊

先看下咱們要作的demo的效果爲:

主要功能模塊爲:

  • 新增計劃,新增一個計劃,編輯區顯示空的計劃內容。

  • 移除計劃,刪除一個計劃以後,計劃列表少了該計劃。

  • 全部計劃的總時長,將全部的計劃時間加起來。

4、項目組件劃分

在原來的目錄結構的調整下,最終的目錄結構爲:

下面詳細介紹下:

一、組件部分

1.首頁組件:Home.vue

<template>
  <div class="jumbotron">
    <h1>個人備忘錄</h1>
    <p>
      <strong>
        <router-link to="/time-entries">建立一個計劃</router-link>
      </strong>
    </p>
  </div>
</template>

2.計算計劃總時長組件:Sidebar.vue

<template>
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3 class="text-center">全部計劃的總時長: {{ time }} 小時</h3>
    </div>

  </div>
</template>

<script>
  export default {
    computed: {
        time() {
          return this.$store.state.totalTime
        }
      }
  }
</script>
View Code

3.計劃列表組件:TimeEntries.vue

<template>
  <div>
    <router-link
      v-if="$route.path !== '/time-entries/log-time'"
      to="/time-entries/log-time"
      class="btn create-plan">
      建立
    </router-link>

    <div v-if="$route.path === '/time-entries/log-time'">
      <h3>新的計劃</h3>
    </div>

    <hr>

    <router-view></router-view>

    <div class="time-entries">
      <p v-if="!plans.length"><strong>尚未任何計劃(┬_┬),快去建立吧ヽ(●-`Д´-)ノ</strong></p>

      <div class="list-group">
        <a class="list-group-item" v-for="(plan,index) in plans">
          <div class="row">
            <div class="col-sm-2 user-details">
              <img :src="plan.avatar" class="avatar img-circle img-responsive" />
              <p class="text-center">
                <strong>
                  {{ plan.name }}
                </strong>
              </p>
            </div>

            <div class="col-sm-2 text-center time-block">
              <p class="list-group-item-text total-time">
                <span class="glyphicon glyphicon-time">計劃總時間:</span>
                {{ plan.totalTime }}
              </p>
              <p class="label label-primary text-center">
                <span class="glyphicon glyphicon-calendar">開始時間:</span>
                {{ plan.date }}
              </p>
            </div>

            <div class="col-sm-7 comment-section">
              <p>備註信息:{{ plan.comment }}</p>
            </div>
              <button
                class="btn btn-xs delete-button"
                @click="deletePlan(index)">
              X
              </button>
          </div>
        </a>

      </div>
    </div>
  </div>
</template>
<script>
    export default {
        name : 'TimeEntries',
        computed : {
          plans () {
            return this.$store.state.list
          }
        },
        methods : {
          deletePlan(idx) {
            // 減去總時間
            this.$store.dispatch('decTotalTime',this.plans[idx].totalTime)
            // 刪除該計劃
            this.$store.dispatch('deletePlan',idx)
          }
        }
    }
</script>
View Code

4.新增計劃組件:LogTime.vue

<template>
  <div class="form-horizontal">
    <div class="form-group">
      <div class="col-sm-6">
        <label>開始日期:</label>
        <input
          type="date"
          class="form-control"
          v-model="date"
          placeholder="Date"
        />
      </div>
      <div class="col-sm-6">
        <label>總時間&nbsp;:</label>
        <input
          type="number"
          class="form-control"
          v-model="totalTime"
          placeholder="Hours"
        />
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-12">
        <label>備註&nbsp;&nbsp;:</label>
        <input
          type="text"
          class="form-control"
          v-model="comment"
          placeholder="Comment"
        />
      </div>
    </div>
    <button class="btn btn-primary" @click="save()">保存</button>
    <router-link to="/time-entries" class="btn btn-danger">取消</router-link>
    <hr>
  </div>
</template>

<script>
  export default {
        name : 'LogTime',
        data() {
            return {
                date : '',
                totalTime : '',
                comment : ''
            }
        },
        methods:{
          save() {
            const plan = {
              name : 'eraser',
              image : 'https://pic.cnblogs.com/avatar/504457/20161108225210.png',
              date : this.date,
              totalTime : this.totalTime,
              comment : this.comment
            };
            this.$store.dispatch('savePlan', plan)
            this.$store.dispatch('addTotalTime', this.totalTime)
            this.$router.go(-1)
          }
        }
    }
</script>
View Code

二、vuex中用來存儲數據的劃分爲:

1.初始化vuex.Store: index.js

import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './actions'

Vue.use(Vuex);

const state = {
  totalTime: 0,
  list: []
};

export default new Vuex.Store({
  state,
  mutations,
  actions
})

State: 單一狀態樹,用一個state對象包含了所有的應用層級狀態,代碼中只new 了一次store實例 Vuex.Store。

2.負責觸發事件和傳入參數:actions.js

import * as types from './mutation-types'

export default {
  addTotalTime({ commit }, time) {
    commit(types.ADD_TOTAL_TIME, time)
  },
  decTotalTime({ commit }, time) {
    commit(types.DEC_TOTAL_TIME, time)
  },
  savePlan({ commit }, plan) {
    commit(types.SAVE_PLAN, plan);
  },
  deletePlan({ commit }, plan) {
    commit(types.DELETE_PLAN, plan)
  }
};
View Code

實踐中,咱們會常常會用到 ES2015 的 參數解構 來簡化代碼(特別是咱們須要調用 commit 不少次的時候):

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

3.註冊各類數據變化的方法: mutations.js

import * as types from './mutation-types'

export default {
    // 增長總時間
  [types.ADD_TOTAL_TIME] (state, time) {
    state.totalTime = state.totalTime + time
  },
  // 減小總時間
  [types.DEC_TOTAL_TIME] (state, time) {
    state.totalTime = state.totalTime - time
  },
  // 新增計劃
  [types.SAVE_PLAN] (state, plan) {
    // 設置默認值,將來咱們能夠作登入直接讀取暱稱和頭像
    const avatar = 'https://pic.cnblogs.com/avatar/504457/20161108225210.png';

    state.list.push(
      Object.assign({ name: 'eraser', avatar: avatar }, plan)
    )
  },
  // 刪除某計劃
  [types.DELETE_PLAN] (state, idx) {
    state.list.splice(idx, 1);
  }
};
View Code

使用常量替代 mutation 事件類型在各類 Flux 實現中是很常見的模式。這樣可使 linter 之類的工具發揮做用,同時把這些常量放在單獨的文件中可讓你的代碼合做者對整個 app 包含的 mutation 一目瞭然:

// mutation-types.js 
export const SOME_MUTATION = 'SOME_MUTATION'

mutations: {
    // 咱們可使用 ES2015 風格的計算屬性命名功能來使用一個常量做爲函數名
 [SOME_MUTATION] (state) { // mutate state  } }

4.記錄全部的事件名: mutation-types.js

// 增長總時間或者減小總時間
export const ADD_TOTAL_TIME = 'ADD_TOTAL_TIME';
export const DEC_TOTAL_TIME = 'DEC_TOTAL_TIME';

// 新增和刪除一條計劃
export const SAVE_PLAN = 'SAVE_PLAN';
export const DELETE_PLAN = 'DELETE_PLAN';
View Code

配合上面常量替代 mutation 事件類型的使用

三、初始化部分

入口文件渲染的模版index.html比較簡單:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>vue-notes-demo</title>
  </head>
  <body>
    <div id="app">
      <router-view></router-view>
    </div>
  </body>
</html>

入口文件main.js的代碼:

import Vue from 'vue';
import App from './App';
import Home from './components/Home';
import TimeEntries from './components/TimeEntries.vue'

import VueRouter from 'vue-router';
import VueResource from 'vue-resource';
import store from './vuex/index';


// 路由模塊和HTTP模塊
Vue.use(VueResource);
Vue.use(VueRouter);

 const routes = [
  { path: '/home', component: Home },
  {
    path : '/time-entries',
    component : TimeEntries,
    children : [{
      path : 'log-time',
      // 懶加載
      component : resolve => require(['./components/LogTime.vue'],resolve),
    }]
  },
  { path: '*', component: Home }
]
const router = new VueRouter({
      routes // short for routes: routes
});
// router.start(App, '#app');
const app = new Vue({
      router,
      store,
       ...App,
}).$mount('#app');
View Code

代碼中 ...App 至關於 render:h => h(App)

初始化組件App.vue爲:

<!-- // src/App.vue -->
<template>
  <div id="wrapper">
    <nav class="navbar navbar-default">
      <div class="container">
        <a class="navbar-brand" href="#">
          <i class="glyphicon glyphicon-time"></i>
          備忘錄
        </a>
        <ul class="nav navbar-nav">
          <li><router-link to="/home">首頁</router-link></li>
          <li><router-link to="/time-entries">計劃列表</router-link></li>
        </ul>
      </div>
    </nav>
    <div class="container">

      <div class="col-sm-9">
        <router-view></router-view>
      </div>
       <div class="col-sm-3">
         <sidebar></sidebar>
      </div>
    </div>
  </div>
</template>

<script>
  import Sidebar from './components/Sidebar.vue'

  export default {
    components: { 'sidebar': Sidebar },
  }
</script>
<style>
.router-link-active {
  color: red;
}
body {
  margin: 0px;
}
.navbar {
  height: 60px;
  line-height: 60px;
  background: #333;

}
.navbar a {
  text-decoration: none;
}
.navbar-brand {
  display: inline-block;
  margin-right: 20px;
  width: 100px;
  text-align: center;
  font-size: 28px;
  text-shadow: 0px 0px 0px #000;
  color: #fff;
  padding-left: 30px;
}
  .avatar {
    height: 75px;
    margin: 0 auto;
    margin-top: 10px;
    /* margin-bottom: 10px; */
  }

  .text-center {
    margin-top: 0px;
    /* margin-bottom: 25px; */
  }

  .time-block {
    /* padding: 10px; */
    margin-top: 25px;
  }
  .comment-section {
    /* padding: 20px; */
    /* padding-bottom: 15px; */
  }

  .col-sm-9 {
    float: right;
    /* margin-right: 60px; */
    width: 700px;
    min-height: 200px;
    background: #ffcccc;
    padding: 60px;
  }
  .create-plan {
    font-size: 26px;
    color: #fff;
    text-decoration: none;
    display: inline-block;
    width: 100px;
    text-align: center;
    height: 40px;
    line-height: 40px;
    background: #99cc99;
  }
  .col-sm-6 {
    margin-top: 10px;
    margin-bottom: 10px;
  }
  .col-sm-12 {
    margin-bottom: 10px;
  }
  .btn-primary {
    width: 80px;
    text-align: center;
    height: 30px;
    line-height: 30px;
    background: #99cc99;
    border-radius: 4px;
    border: none;
    color: #fff;
    float: left;
    margin-right: 10px;
    font-size: 14px;
  }
  .btn-danger {
    display: inline-block;
    font-size: 14px;
    width: 80px;
    text-align: center;
    height: 30px;
    line-height: 30px;
    background: red;
    border-radius: 4px;
    text-decoration: none;
    color: #fff;
    margin-bottom: 6px;
  }
  .row {
    padding-bottom: 20px;
    border-bottom: 1px solid #333;
    position: relative;
    background: #f5f5f5;
    padding: 10px;
    /* padding-bottom: 0px; */
  }
  .delete-button {
    position: absolute;
    top: 10px;
    right: 10px;
  }
  .panel-default {
    position: absolute;
    top: 140px;
    right: 60px;
  }
</style>
View Code

至此,實踐結束,一些原理性的東西我還須要多去理解^_^

源代碼:【vuex2.0實踐】

參考:

vue2.0構建單頁應用最佳實戰

vuex2.0文檔

http://www.cnblogs.com/lvyongbo/p/5946271.html

相關文章
相關標籤/搜索