vuex 結構分析
Vuex項目實戰
mian.js
/*
入口JS
*/
import Vue from 'vue'
import App from './App.vue'
import store from './store'
import './base.css'
// 創建vm
/* eslint-disable no-new */
new Vue({
el: '#app',
components: {App}, // 映射組件標籤
template: '<App/>', // 指定需要渲染到頁面的模板
store // 所有的組件對象都多了一個屬性: $store(值就是store對象)
})
base.css
body {
background: #fff;
}
.btn {
display: inline-block;
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
text-align: center;
vertical-align: middle;
cursor: pointer;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
border-radius: 4px;
}
.btn-danger {
color: #fff;
background-color: #da4f49;
border: 1px solid #bd362f;
}
.btn-danger:hover {
color: #fff;
background-color: #bd362f;
}
.btn:focus {
outline: none;
}
組件App.vue
<template>
<div class="todo-container">
<div class="todo-wrap">
<TodoHeader/>
<TodoList/>
<TodoFooter/>
</div>
</div>
</template>
<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoList from './components/TodoList.vue'
import TodoFooter from './components/TodoFooter.vue'
export default {
components: {
TodoHeader,
TodoList,
TodoFooter
}
}
</script>
<style>
.todo-container {
width: 600px;
margin: 0 auto;
}
.todo-container .todo-wrap {
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
</style>
\components\TodoFooter.vue
<template>
<div class="todo-footer">
<label>
<input type="checkbox" v-model="checkAll"/>
</label>
<span>
<span>已完成{{completeSize}}</span> / 全部{{totalSize}}
</span>
<button class="btn btn-danger" v-show="completeSize" @click="deleteAllCompleted">清除已完成任務</button>
</div>
</template>
<script>
import {mapGetters} from 'vuex'
export default {
computed: {
...mapGetters(['totalSize', 'completeSize']),
checkAll: {
get () { // 決定是否勾選
return this.$store.getters.isAllSelect
},
set (value) {// 點擊了全選checkbox value是當前checkbox的選中狀態(true/false)
// this.selectAll(value)
this.$store.dispatch('selectAll', value)
}
},
},
methods: {
deleteAllCompleted () {
if(window.confirm('確定清除已完成的嗎?')) {
// this.deleteCompleteTodos()
this.$store.dispatch('deleteCompleteTodos')
}
}
}
}
</script>
<style>
.todo-footer {
height: 40px;
line-height: 40px;
padding-left: 6px;
margin-top: 5px;
}
.todo-footer label {
display: inline-block;
margin-right: 20px;
cursor: pointer;
}
.todo-footer label input {
position: relative;
top: -1px;
vertical-align: middle;
margin-right: 5px;
}
.todo-footer button {
float: right;
margin-top: 5px;
}
</style>
\components\TodoHeader.vue
<template>
<div class="todo-header">
<input type="text" placeholder="請輸入你的任務名稱,按回車鍵確認" v-model="inputTodo" @keyup.enter="add"/>
</div>
</template>
<script>
export default {
data () {
return {
inputTodo: '' // 不需要使用vuex管理(只有當前組件使用)
}
},
methods: {
add () {
// 得到輸入的數據
const inputTodo = this.inputTodo.trim()
// 檢查合法性
if(!inputTodo) {
alert('必須輸入')
return
}
// 封裝一個todo對象
const todo = {
title: inputTodo,
complete: false
}
// 添加到todos中顯示
// this.addTodo(todo)
this.$store.dispatch('addTodo', todo)
// 清除輸入
this.inputTodo = ''
}
}
}
</script>
<style>
.todo-header input {
width: 560px;
height: 28px;
font-size: 14px;
border: 1px solid #ccc;
border-radius: 4px;
padding: 4px 7px;
}
.todo-header input:focus {
outline: none;
border-color: rgba(82, 168, 236, 0.8);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
}
</style>
\components\TodoItem.vue
<template>
<li :style="{background: bgColor}" @mouseenter="handleEnter(true)" @mouseleave="handleEnter(false)">
<label>
<input type="checkbox" v-model="todo.complete"/>
<span>{{todo.title}}</span>
</label>
<button class="btn btn-danger" v-show="isShow" @click="deleteItem">刪除</button>
</li>
</template>
<script>
export default {
props: {// 指定屬性名和屬性值的類型
todo: Object,
index: Number
},
data () {
return {
bgColor: 'white',
isShow: false
}
},
methods: {
handleEnter (isEnter) {
if(isEnter) { // 進入
this.bgColor = '#cccccc'
this.isShow = true
} else { // 離開
this.bgColor = '#ffffff'
this.isShow = false
}
},
deleteItem () {
// this.deleteTodo(this.index)
this.$store.dispatch('deleteTodo', this.index)
}
}
}
</script>
<style>
li {
list-style: none;
height: 36px;
line-height: 36px;
padding: 0 5px;
border-bottom: 1px solid #ddd;
}
li label {
float: left;
cursor: pointer;
}
li label li input {
vertical-align: middle;
margin-right: 6px;
position: relative;
top: -1px;
}
li button {
float: right;
display: none;
margin-top: 3px;
}
li:before {
content: initial;
}
li:last-child {
border-bottom: none;
}
</style>
\components\TodoList.vue
<template>
<ul class="todo-main">
<TodoItem v-for="(todo, index) in todos" :key="index"
:todo="todo" :index="index"/>
</ul>
</template>
<script>
import {mapState} from 'vuex'
import TodoItem from './TodoItem.vue'
import storageUtils from '../utils/storageUtils'
export default {
computed: {
...mapState(['todos'])
},
watch: {
todos: {
deep: true, // 深度監視
handler: storageUtils.saveTodos,
}
},
components: {
TodoItem
}
}
</script>
<style>
.todo-main {
margin-left: 0px;
border: 1px solid #ddd;
border-radius: 2px;
padding: 0px;
}
.todo-empty {
height: 40px;
line-height: 40px;
border: 1px solid #ddd;
border-radius: 2px;
padding-left: 5px;
margin-top: 10px;
}
</style>
\store\actions.js
/*
包含n個用於間接更新狀態的方法的對象模塊
*/
import {ADD_TODO, DELETE_TODO, SELECT_ALL_TODOS, DELETE_COMPLETE_TODOS} from './mutation-types'
export default {
addTodo ({commit}, todo) {
// 提交一個comutation請求
commit(ADD_TODO, {todo}) // 傳遞給mutation的是一個包含數據的對象
},
deleteTodo ({commit}, index) {
commit(DELETE_TODO, {index})
},
selectAll ({commit}, isCheck) {
commit(SELECT_ALL_TODOS, {isCheck})
},
deleteCompleteTodos ({commit}) {
commit(DELETE_COMPLETE_TODOS)
}
}
\store\getters.js
/*
包含n個基於state的getter計算屬性方法的對象模塊
*/
export default {
// 總數量
totalSize (state) {
return state.todos.length
},
// 完成的數量
completeSize (state) {
return state.todos.reduce((preTotal, todo) => preTotal + (todo.complete?1:0) ,0)
},
// 判斷是否需要全選
isAllSelect (state, getters) {
return getters.completeSize===getters.totalSize && getters.completeSize>0
}
}
\store\index.js
/*
vuex核心管理模塊store對象
*/
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
Vue.use(Vuex)
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
\store\mutations.js
/*
包含n個用於直接更新狀態的方法的對象模塊
*/
import {ADD_TODO, DELETE_TODO, SELECT_ALL_TODOS, DELETE_COMPLETE_TODOS} from './mutation-types'
export default {
[ADD_TODO] (state, {todo}) { // 方法名不是ADD_TODO, 而是add_todo
state.todos.unshift(todo)
},
[DELETE_TODO] (state, {index}) {
state.todos.splice(index, 1)
},
[SELECT_ALL_TODOS] (state, {isCheck}) {
state.todos.forEach(todo => todo.complete = isCheck)
},
[DELETE_COMPLETE_TODOS] (state) {
state.todos = state.todos.filter(todo => !todo.complete)
}
}
\store\mutation-types.js
/*
包含n個mutation名稱常量
*/
export const ADD_TODO = 'add_todo' // 添加todo
export const DELETE_TODO = 'delete_todo' // 刪除todo
export const SELECT_ALL_TODOS = 'select_all_todos' // 全選/全不選todos
export const DELETE_COMPLETE_TODOS = 'delete_complete_todos' // 刪除所有選中的
\store\state.js
/*
狀態對象模塊
*/
import storageUtils from '../utils/storageUtils'
export default {
todos: storageUtils.readTodos()
}
\utils\storageUtils.js
/*
向local中存儲數據的工具模塊
1. 向外暴露一個函數(功能)
只有一個功能需要暴露
2. 向外暴露一個對象(包含多個功能)
有多個功能需要暴露
*/
const TODOS_KEY = 'todos_key'
export default {
readTodos () {
return JSON.parse(localStorage.getItem(TODOS_KEY) || '[]')
},
saveTodos (todos) {
localStorage.setItem(TODOS_KEY, JSON.stringify(todos))
}
}