人之贤不肖譬如鼠矣,在所自处耳!――《李斯列传》
聊聊vuex
,官方文档:https://vuex.vuejs.org/zh/
介绍就不赘述了,直接上使用
安装:
1
| cnpm install vuex --save
|
我们新建一个store
,再创建一个index.js
再新建一个modules
目录,里面放上 value.js
在main.js
中我们写入
1 2 3 4 5 6 7 8 9 10 11 12
| import Vue from 'vue' import App from './App.vue' import router from '@/router' import store from '@/store';
Vue.config.productionTip = false
new Vue({ router, store, render: h => h(App) }).$mount('#app')
|
挂载完毕后,我们编写main.js
和value.js
main.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import Vue from 'vue'; import Vuex from 'vuex';
Vue.use(Vuex);
import ruben from '@/store/modules/value.js'
export default new Vuex.Store({ modules: { ruben } });
|
value.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
export default { state: { value: 'hello' }, getters: { getValue: state => state.value }, mutations: { setValue(state, value) { state.value = value } }, actions: { submitValue(context, value) { console.log("context: ", context); return new Promise((resolve, reject) => setTimeout(() => { context.commit('setValue', value); resolve(value); }, 1000)) } } }
|
去掉注释长这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| export default { state: { value: 'hello' }, getters: { getValue: state => state.value }, mutations: { setValue(state, value) { state.value = value } }, actions: { submitValue(context, value) { console.log("context: ", context); return new Promise((resolve, reject) => setTimeout(() => { context.commit('setValue', value); resolve(value); }, 1000)) } } }
|
然后我们找个页面引用一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| <template></template>
<script> import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'; export default { computed: { ...mapState({ value: state => state.ruben.value }), ...mapGetters(['getValue']) }, methods: { ...mapMutations(['setValue']), ...mapActions(['submitValue']) }, created() { console.log('this: ', this); // state console.log('this.value: ', this.value); console.log('this.$store.state.value: ', this.$store.state.ruben.value); // mutations this.setValue('ruben'); this.$store.commit('setValue', 'ruben'); // getters console.log('this.getValue: ', this.getValue); console.log('this.$store.getters.getValue: ', this.$store.getters.getValue); // actions this.submitValue('achao').then(console.log); this.$store.dispatch('submitValue','achao').then(console.log); } }; </script>
<style></style>
|
我们看输出结果