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

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

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

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

結(jié)果為:

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

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

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

下面詳細(xì)介紹下:
1、組件部分
1).首頁(yè)組件:Home.vue
<template> <div class="jumbotron"> <h1>我的備忘錄</h1> <p> <strong> <router-link to="/time-entries">創(chuàng)建一個(gè)計(jì)劃</router-link> </strong> </p> </div> </template>
2).計(jì)算計(jì)劃總時(shí)長(zhǎng)組件:Sidebar.vue
<template>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="text-center">所有計(jì)劃的總時(shí)長(zhǎng): {{ time }} 小時(shí)</h3>
</div>
</div>
</template>
<script>
export default {
computed: {
time() {
return this.$store.state.totalTime
}
}
}
</script>
3).計(jì)劃列表組件: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>新的計(jì)劃</h3>
</div>
<hr>
<router-view></router-view>
<div class="time-entries">
<p v-if="!plans.length"><strong>還沒(méi)有任何計(jì)劃(┬_┬),快去創(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">計(jì)劃總時(shí)間:</span>
{{ plan.totalTime }}
</p>
<p class="label label-primary text-center">
<span class="glyphicon glyphicon-calendar">開(kāi)始時(shí)間:</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) {
// 減去總時(shí)間
this.$store.dispatch('decTotalTime',this.plans[idx].totalTime)
// 刪除該計(jì)劃
this.$store.dispatch('deletePlan',idx)
}
}
}
</script>
4).新增計(jì)劃組件:LogTime.vue
<template>
<div class="form-horizontal">
<div class="form-group">
<div class="col-sm-6">
<label>開(kāi)始日期:</label>
<input
type="date"
class="form-control"
v-model="date"
placeholder="Date"
/>
</div>
<div class="col-sm-6">
<label>總時(shí)間 :</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中用來(lái)存儲(chǔ)數(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)樹(shù),用一個(gè)state對(duì)象包含了全部的應(yīng)用層級(jí)狀態(tài),代碼中只new 了一次store實(shí)例 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)
}
};
實(shí)踐中,我們會(huì)經(jīng)常會(huì)用到 ES2015 的 參數(shù)解構(gòu) 來(lái)簡(jiǎn)化代碼(特別是我們需要調(diào)用 commit 很多次的時(shí)候):
actions: {
increment ({ commit }) {
commit('increment')
}
}
3).注冊(cè)各種數(shù)據(jù)變化的方法: mutations.js
import * as types from './mutation-types'
export default {
// 增加總時(shí)間
[types.ADD_TOTAL_TIME] (state, time) {
state.totalTime = state.totalTime + time
},
// 減少總時(shí)間
[types.DEC_TOTAL_TIME] (state, time) {
state.totalTime = state.totalTime - time
},
// 新增計(jì)劃
[types.SAVE_PLAN] (state, plan) {
// 設(shè)置默認(rèn)值,未來(lái)我們可以做登入直接讀取昵稱(chēng)和頭像
const avatar = 'https://pic.cnblogs.com/avatar/504457/20161108225210.png';
state.list.push(
Object.assign({ name: 'eraser', avatar: avatar }, plan)
)
},
// 刪除某計(jì)劃
[types.DELETE_PLAN] (state, idx) {
state.list.splice(idx, 1);
}
};
使用常量替代 mutation 事件類(lèi)型在各種 Flux 實(shí)現(xiàn)中是很常見(jiàn)的模式。這樣可以使 linter 之類(lèi)的工具發(fā)揮作用,同時(shí)把這些常量放在單獨(dú)的文件中可以讓你的代碼合作者對(duì)整個(gè) app 包含的 mutation 一目了然:
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
mutations: {
// 我們可以使用 ES2015 風(fēng)格的計(jì)算屬性命名功能來(lái)使用一個(gè)常量作為函數(shù)名
[SOME_MUTATION] (state) {
// mutate state
}
}
4).記錄所有的事件名: mutation-types.js
// 增加總時(shí)間或者減少總時(shí)間 export const ADD_TOTAL_TIME = 'ADD_TOTAL_TIME'; export const DEC_TOTAL_TIME = 'DEC_TOTAL_TIME'; // 新增和刪除一條計(jì)劃 export const SAVE_PLAN = 'SAVE_PLAN'; export const DELETE_PLAN = 'DELETE_PLAN';
配合上面常量替代 mutation 事件類(lèi)型的使用
3、初始化部分
入口文件渲染的模版index.html比較簡(jiǎn)單:
<!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">首頁(yè)</router-link></li>
<li><router-link to="/time-entries">計(jì)劃列表</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>
至此,實(shí)踐結(jié)束,一些原理性的東西我還需要多去理解^_^
源代碼:【vuex2.0實(shí)踐】
參考:
vue2.0構(gòu)建單頁(yè)應(yīng)用最佳實(shí)戰(zhàn)
關(guān)于Vue.js 2.0的Vuex 2.0 你需要更新的知識(shí)庫(kù)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
mpvue跳轉(zhuǎn)頁(yè)面及注意事項(xiàng)
這篇文章主要介紹了mpvue跳轉(zhuǎn)頁(yè)面及注意事項(xiàng)的相關(guān)資料,需要的朋友可以參考下2018-08-08
vue3+vite+vant4手機(jī)端項(xiàng)目實(shí)戰(zhàn)記錄
這篇文章主要給大家介紹了關(guān)于vue3+vite+vant4手機(jī)端項(xiàng)目實(shí)戰(zhàn)的相關(guān)資料,Vue3是一種前端開(kāi)發(fā)框架,它的目標(biāo)是提供更好的性能和開(kāi)發(fā)體驗(yàn),需要的朋友可以參考下2023-08-08
vue2.0 與 bootstrap datetimepicker的結(jié)合使用實(shí)例
本篇文章主要介紹了vue2.0 與 bootstrap datetimepicker的結(jié)合使用實(shí)例,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-05-05
vue2和vue3的v-if與v-for優(yōu)先級(jí)對(duì)比學(xué)習(xí)
這篇文章主要介紹了vue2和vue3的v-if與v-for優(yōu)先級(jí)對(duì)比學(xué)習(xí),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
詳解Vue Elememt-UI構(gòu)建管理后臺(tái)
本篇文章給大家詳細(xì)分享了Vue Elememt-UI構(gòu)建管理后臺(tái)的過(guò)程以及相關(guān)代碼實(shí)例,一起參考學(xué)習(xí)下。2018-02-02
Vue keepAlive頁(yè)面強(qiáng)制刷新方式
這篇文章主要介紹了Vue keepAlive頁(yè)面強(qiáng)制刷新方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05

