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>