1、概述
Vuex作為插件,管理和維護整個項目的組件狀態。
2、安裝vuex
cnpm i --save vuex
3、vuex使用
github地址:https://github.com/MengFangui/Vuex
new Vue({ el: '#app', router: router, //使用vuex
store: store, render: h => { return h(App) } });
4、配置項
(1)數據:數據保存在state中。store的數據只能讀取,不能改變。
(2)改變store中的數據使用mutations。組件內通過this.$store.commit來執行mutations.
(3)getters:提取過濾方法。
(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) }) } } });
5、組件代碼
<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 維護多個組件之間的公共(共有)狀態!