0,原本想只用vue就能夠作項目了,後來發現不行;一個網頁被切分紅若干個組件,組件之間是須要數據傳遞的,所以引入了vuex這個集中式存儲、管理的狀態管理模式。javascript
1,安裝vuex:vue
npm install --save vuex
在main.js中引入:java
import Vuex from 'vuex' Vue.use(Vuex)
2,建立數據源文件vuex/store.jsvuex
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ // 定義狀態 state: { msg: '我是Hello模塊' }, // 改變狀態 mutations: { setMsg(state,msg){ state.msg = msg } } }) export default store
並在main.js 中引入npm
import store from './vuex/store' Vue.prototype.$store = store
3,重寫hello.vue,使用vuex管理的狀態變量bash
<template> <div class="hello"> <h2>{{ msg }}</h2> <ul> <li><a href="#/game">我是一個連接</a></li> </ul> </div> </template> <script> export default { name: 'hello', data () { return { msg: this.$store.state.msg //我是Hello模塊 } } } </script>
4,在 game.vue 中改變這個狀態變量的值this
<template> <div class="game"> <h2>{{ msg }}</h2> <ul> <li><a href="#/">返回</a></li> </ul> </div> </template> <script> export default { name: 'game', data () { return { msg: '我是Game模塊' } }, mounted:function(){ this.sendMsg() }, methods:{ sendMsg:function(e){ this.$store.commit('setMsg',this.msg);//改變狀態 } } } </script>
hello.vue中的msg被從新設置。prototype
解決了組件之間的通訊問題,就能夠大膽地合理規劃組件拉。^_^blog