Vuex2.0+Vue2.0構(gòu)建備忘錄應(yīng)用實踐
一、介紹Vuex
Vuex 是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化,適合于構(gòu)建中大型單頁應(yīng)用。
1、什么是狀態(tài)管理模式?
看個簡單的例子:
<!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>
<!-- 2、view,映射到視圖的數(shù)據(jù)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({
// 1、state,驅(qū)動應(yīng)用的數(shù)據(jù)源;
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
}
},
// 3、actions,響應(yīng)在view上的用戶輸入導(dǎo)致的狀態(tài)變化。
actions: {
increment: function({ dispatch, state }){
dispatch('INCREMENT', 1)
},
decrement: function({ dispatch, state }){
dispatch('DECREMENT', 1)
}
}
}
})
</script>
</html>
代碼中標(biāo)識了:
1、state,驅(qū)動應(yīng)用的數(shù)據(jù)源;
2、view,映射到視圖的數(shù)據(jù)counterValue;
3、actions,響應(yīng)在view上的用戶輸入導(dǎo)致的狀態(tài)變化。
用簡單示意圖表示他們之間的關(guān)系:

我們知道,中大型的應(yīng)用一般會遇到多個組件共享同一狀態(tài)的情況:
1、多個視圖依賴于同一狀態(tài)
2、來自不同視圖的行為需要變更同一狀態(tài)
于是需要把組件的共享狀態(tài)抽取出來,以一個全局單例模式管理,另外,需要定義和隔離狀態(tài)管理中的各種概念并強(qiáng)制遵守一定的規(guī)則。
這就是 Vuex 背后的基本思想,借鑒了 Flux、Redux、和 The Elm Architecture。與其他模式不同的是,Vuex 是專門為 Vue.js 設(shè)計的狀態(tài)管理庫,以利用 Vue.js 的細(xì)粒度數(shù)據(jù)響應(yīng)機(jī)制來進(jìn)行高效的狀態(tài)更新。

2、Vuex的核心概念
1)、State: 單一狀態(tài)樹,用一個對象包含了全部的應(yīng)用層級狀態(tài),作為一個『唯一數(shù)據(jù)源(SSOT)』而存在,每個應(yīng)用將僅僅包含一個 store 實例。
2)、Getters: Vuex 允許我們在 store 中定義『getters』(可以認(rèn)為是 store 的計算屬性)。
3)、Mutations: Vuex 中的 mutations 非常類似于事件:每個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調(diào)函數(shù) (handler)。這個回調(diào)函數(shù)就是我們實際進(jìn)行狀態(tài)更改的地方,并且它會接受 state 作為第一個參數(shù)。
4)、Actions: 類似于 mutation,不同在于:①Action 提交的是 mutation,而不是直接變更狀態(tài);②Action 可以包含任意異步操作。
5)、Modules: 為解決單一狀態(tài)樹導(dǎo)致應(yīng)用的所有狀態(tài)集中在一個store對象的臃腫問題,Vuex將store分割到模塊(module)。每個模塊擁有自己的 state、mutation、action、getters、甚至是嵌套子模塊——從上至下進(jìn)行類似的分割。
接著我們開始構(gòu)建備忘錄應(yīng)用,在以下構(gòu)建過程的介紹中,再加深理解上述概念。
二、環(huán)境安裝
1.安裝 vue-cli

2.初始化應(yīng)用
vue init webpack vue-notes-demo cd vue-notes-demo npm install // 安裝依賴包 npm run dev // 啟動服務(wù)

結(jié)果為:

目錄結(jié)構(gòu)為:

三、功能模塊
先看下我們要做的demo的效果為:

主要功能模塊為:
新增計劃,新增一個計劃,編輯區(qū)顯示空的計劃內(nèi)容。
移除計劃,刪除一個計劃之后,計劃列表少了該計劃。
所有計劃的總時長,將所有的計劃時間加起來。
四、項目組件劃分
在原來的目錄結(jié)構(gòu)的調(diào)整下,最終的目錄結(jié)構(gòu)為:

下面詳細(xì)介紹下:
1、組件部分
1).首頁組件:Home.vue
<template> <div class="jumbotron"> <h1>我的備忘錄</h1> <p> <strong> <router-link to="/time-entries">創(chuàng)建一個計劃</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>
3).計劃列表組件:TimeEntries.vue
<template>
<div>
<router-link
v-if="$route.path !== '/time-entries/log-time'"
to="/time-entries/log-time"
class="btn create-plan">
創(chuàng)建
</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>還沒有任何計劃(┬_┬),快去創(chuàng)建吧ヽ(●-`Д´-)ノ</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>
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>總時間 :</label>
<input
type="number"
class="form-control"
v-model="totalTime"
placeholder="Hours"
/>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<label>備注 :</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>
2、vuex中用來存儲數(shù)據(jù)的劃分為:
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: 單一狀態(tài)樹,用一個state對象包含了全部的應(yīng)用層級狀態(tài),代碼中只new 了一次store實例 Vuex.Store。
2).負(fù)責(zé)觸發(fā)事件和傳入?yún)?shù):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)
}
};
實踐中,我們會經(jīng)常會用到 ES2015 的 參數(shù)解構(gòu) 來簡化代碼(特別是我們需要調(diào)用 commit 很多次的時候):
actions: {
increment ({ commit }) {
commit('increment')
}
}
3).注冊各種數(shù)據(jù)變化的方法: 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) {
// 設(shè)置默認(rèn)值,未來我們可以做登入直接讀取昵稱和頭像
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);
}
};
使用常量替代 mutation 事件類型在各種 Flux 實現(xiàn)中是很常見的模式。這樣可以使 linter 之類的工具發(fā)揮作用,同時把這些常量放在單獨的文件中可以讓你的代碼合作者對整個 app 包含的 mutation 一目了然:
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
mutations: {
// 我們可以使用 ES2015 風(fēng)格的計算屬性命名功能來使用一個常量作為函數(shù)名
[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';
配合上面常量替代 mutation 事件類型的使用
3、初始化部分
入口文件渲染的模版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');
代碼中 ...App 相當(dāng)于 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>
至此,實踐結(jié)束,一些原理性的東西我還需要多去理解^_^
源代碼:【vuex2.0實踐】
參考:
vue2.0構(gòu)建單頁應(yīng)用最佳實戰(zhàn)
關(guān)于Vue.js 2.0的Vuex 2.0 你需要更新的知識庫
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue3+vite+vant4手機(jī)端項目實戰(zhàn)記錄
這篇文章主要給大家介紹了關(guān)于vue3+vite+vant4手機(jī)端項目實戰(zhàn)的相關(guān)資料,Vue3是一種前端開發(fā)框架,它的目標(biāo)是提供更好的性能和開發(fā)體驗,需要的朋友可以參考下2023-08-08
vue2.0 與 bootstrap datetimepicker的結(jié)合使用實例
本篇文章主要介紹了vue2.0 與 bootstrap datetimepicker的結(jié)合使用實例,非常具有實用價值,需要的朋友可以參考下2017-05-05
vue2和vue3的v-if與v-for優(yōu)先級對比學(xué)習(xí)
這篇文章主要介紹了vue2和vue3的v-if與v-for優(yōu)先級對比學(xué)習(xí),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10

