個人vx學習總結
vuex最大的作用就是為了讓兩個不相干的元件也能進行資料共享,vuex主要是怎麼做的呢
定義狀態 => 方法改變狀態 => 什麼時候改變狀態 => vue頁面獲取狀態
先在js檔案寫入以下程式碼
const state = {
money: 1
}
const mutations = {
add(state,param) {
console.log(param)
state.money++
},
reduce(state) {
state.money--
}
}
const actions = {
add: ({commit},param) => {
commit('add',param)
},
reduce: ({commit}) => {
commit('reduce')
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
然後在總index.js檔案裡匯入模組跟包
import Vue from 'vue'
import Vuex from 'vuex'
import money from './modules/a'
import count from './modules/b'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
money,
count
}
})
然後main.js引入到App.vue頁面裡
import Vue from 'vue'
import App from './App.vue'
import store from './store/index'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
store
}).$mount('#app')
在到App.vue引入模組
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
<!-- <Vuexx /> -->
<pagea />
<pageb />
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
// import Vuexx from './components/vuex.vue'
import pagea from './components/a.vue'
import pageb from './components/b.vue'
import './components/n.js'
export default {
name: 'app',
components: {
HelloWorld,
pagea,
pageb
}
}
</script>
在到a.js進行vuex狀態獲取跟引數的傳遞
<template lang="html">
<div>
<div class="a">page a {{ $store.state.money.money }} {{ $store.state.count.count }}</div>
<button @click="add(2)">+</button>
<button @cllick="reduce">-</button>
</div>
</template>
<script type="text/javascript">
import { mapActions } from 'vuex'
export default{
methods: mapActions('money',['add','reduce'])
}
</script>