一、概述vue
Vuex做爲插件,管理和維護整個項目的組件狀態。git
二、安裝vuexgithub
cnpm i --save vuexvuex
三、vuex使用npm
github地址:https://github.com/MengFangui/Vuexapp
new Vue({ el: '#app', router: router, //使用vuex
store: store, render: h => { return h(App) } });
四、配置項異步
(1)數據:數據保存在state中。store的數據只能讀取,不能改變。async
(2)改變store中的數據使用mutations。組件內經過this.$store.commit來執行mutations.ui
(3)getters:提取過濾方法。this
(4)actions:處理異步操做,組件內經過this.$store.dispatch觸發。
涉及數據改變的用mutations,涉及業務邏輯的使用actions。
以上總體配置爲:
//vuex的配置 //注意Store是大寫
const store = new Vuex.Store({ //數據保存
state: { count: 0, list: [1, 5, 8, 10, 30, 50] }, mutations: { increase(state, n = 1) { state.count += n; }, decrease(state, n = 1) { state.count -= n; } }, getters: { filteredList: state => { return state.list.filter(item => item < 10); } }, actions:{ asyncIncrease(context){ //異步 1s後執行
return new Promise(resolve=>{ setTimeout(()=>{ context.commit('increase'); //Promise 的一種狀態Resolved(已完成)
resolve(); },1000) }) } } });
五、組件代碼
<template>
<div>
<h1>首頁</h1> {{count}} <button @click="handleIncrease">+5</button>
<button @click="handleDecrease">-5</button>
<!--getters 用法-->
<div>{{list}}</div>
<!--actions用法-->
<button @click="handleAsyncIncrease">action +1</button>
<!--router-link會渲染爲一個a標籤 實現跳轉的方式1-->
<!--router-link 的tag屬性 指定渲染成什麼標籤-->
<!--router-link 的replace屬性 不會留下history記錄,不能使用後退鍵-->
<!--router-link 的active-class屬性 路由匹配成功時會自動給當前元素設置爲一個名爲router-link-active的class-->
<router-link to="/about">跳轉到 about</router-link>
</div>
</template>
<script> export default { computed:{ count(){ return this.$store.state.count; }, list(){ return this.$store.getters.filteredList; } }, methods:{ handleIncrease(){ this.$store.commit('increase',5); }, handleDecrease(){ this.$store.commit('decrease',5); }, handleAsyncIncrease(){ this.$store.dispatch('asyncIncrease').then(()=>{ console.log(this.$store.state.count) }); } } } </script>
vuex 維護多個組件之間的公共(共有)狀態!