vuexµÄÀíÂÛ֪ʶ¾Í²»¶àÌáÁË£¬¹ÙÍøÉÏÒѾÓÐÃ÷È·µÄ½²½â¡£
ÓÃÒ»¸ö¼òµ¥µÄÀý×ÓÀ´ÃèÊöһϻù±¾µÄÓ÷¨:
µÚÒ»²½£ºnpm install vuex ¨Csave-dev
µÚ¶þ²½£ºÔÚĿ¼Öд´½¨storeĿ¼ÅäÖùÜÀí״̬
//store/index.js /** * Created by zhaohuan on 2017/7/13. */ import Vue from 'vue' import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { msg: 'ÔʼÊý¾Ý' }, actions: { fun: function ({commit},date) { commit('saveAdminInfo', {list: date}); }, }, mutations: { saveAdminInfo(state, adminInfo){ state.msg = adminInfo.list; } } }); export default store;
µÚÈý²½£ºÔÚmain.jsÖÐÒýÈëstore
new Vue({ el: '#app', router, store, template: '<App/>', components: { App } });
µÚËIJ¿£º±àд·ÓÉÒ³Ãæ
//test1.vue <template> <div> msg:{{msg}} <input type="text" v-model="checkedNames" style="border: 1px solid red"> <button @click="fun">Ìá½»</button> </div> </template> <script> import {mapState,mapActions} from 'vuex'; export default{ data(){ return{ checkedNames:'' } } , computed: {...mapState(['msg'])}, methods: { // ...mapActions(['fun'])£» //Èç¹ûÐèÒªÏòactionsÀïÃæ´«Öµ¾ÍÊÖ¶¯µ÷Óà fun(){ this.$store.dispatch('fun',this.checkedNames); } //...mapActions(['fun']£©== this.$store.dispatch('fun'); } } </script>
test2.vue
<template> <div> msg:{{msg}} </div> </template> <script> import {mapState} from 'vuex'; export default{ computed: {...mapState(['msg'])}, //¶ÔÓ¦getters.¼¼ÊõÖеÄmsg // methods: {...mapActions(['fun'])} } </script>
ÐÞ¸Ä֮ǰ£º
test1
test2
ÒÔÉÏÕâƪdz̸vuexµÄ»ù±¾Ó÷¨ºÍmapaction´«ÖµÎÊÌâ¾ÍÊÇС±à·ÖÏí¸ø´ó¼ÒµÄÈ«²¿ÄÚÈÝÁË£¬Ï£ÍûÄܸø´ó¼ÒÒ»¸ö²Î¿¼£¬Ò²Ï£Íû´ó¼Ò¶à¶àÖ§³Ö½Å±¾Ö®¼Ò¡£
转载请注明:谷谷点程序 » 浅谈vuex的基本用法和mapaction传值问题