https://vuex.vuejs.org/zh-cn/vue
https://github.com/itguide/vu...webpack
Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式。它採用集中式存儲管理應用的全部組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。Vuex 也集成到 Vue 的官方調試工具 devtools extension,提供了諸如零配置的 time-travel 調試、狀態快照導入導出等高級調試功能。git
想一想一下,angular裏面的service
controller -> service
在service 裏面請求api
在controller裏面調用service
service1
好比github
controller1 -> service1 controller2 -> service1
若是你把驅動應用的數據源如今寫在一個組件裏面,只針對這個組件來用。
若是寫在vuex裏面的state 裏面,任何組件均可以調用。web
雖然 Vuex 能夠幫助咱們管理共享狀態,但也附帶了更多的概念和框架。這須要對短時間和長期效益進行權衡。 若是您不打算開發大型單頁應用,使用 Vuex 多是繁瑣冗餘的。確實是如此——若是您的應用夠簡單,您最好不要使用 Vuex。一個簡單的 global event bus 就足夠您所需了。可是,若是您須要構建是一箇中大型單頁應用,您極可能會考慮如何更好地在組件外部管理狀態,Vuex 將會成爲天然而然的選擇。引用 Redux 的做者 Dan Abramov 的話說就是:
Flux 架構就像眼鏡:您自會知道何時須要它。vue-router
https://github.com/itguide/vu...vuex
npm install vuex --save
yarn add vuex
在一個模塊化的打包系統中,您必須顯式地經過 Vue.use() 來安裝 Vuex:chrome
vue init webpack vuexbasenpm
在項目文件中src裏面api
index.js 文件內容以下
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) let store = new Vuex.Store({ state: { num: 100 } }) export default store
import Vue from 'vue' import App from './App' import router from './router' import store from './store' //引入vuex Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, // 須要在添加 template: '<App/>', components: { App } })
https://chrome.google.com/web...
Increment.vue
<template> <div> <h2>加減法計算器</h2> <div> <input type="button" value="-" @click="minHandle"/> <span>{{num}}</span> <input type="button" value="+" @click="addHandle"/> </div> </div> </template> <script> export default { data(){ return { // num:100 num: this.$store.state.num, } }, methods:{ addHandle(){ this.num += 5; }, minHandle(){ this.num -= 5; } } } </script>
import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import Increment from '@/components/Increment' Vue.use(Router) export default new Router({ routes: [{ path: '/', name: 'Hello', component: Increment }] })
$store 在main裏面引入了以後,記得在 在這個裏面加入 new Vue({ el: '#app', router, store, // 須要在添加 template: '<App/>', components: { App } }) 在組件調用方式: this.$store.state.num
此時就運行項目會發現以下
npm run dev