vuex的mapState,mapGetters,mapActions,mapMutations与模块化

mapState 和mapGetters

  • 用于生成计算属性computed
  • mapState({“计算属性名”:“State数据”,“xxx”:“xxxx”,…}),返回的是一系列函数
  • mapState([‘计算属性和State里数据同名’,“xxxx”,“xxx”,…])此处为简写形式
  • mapGetters用法基本一致

vuex的mapState,mapGetters,mapActions,mapMutations与模块化_第1张图片

  • 通过mapState,mapGetters生成的数据为vuex bindings

  • import {mapState,mapGetters} from 'vuex'
    computed:{
      s(){return 500},
      ...mapState({sum1:"sum"}),
      ...mapState(["sum"]),
      ...mapGetters({bigsum1:"bigsum"}),
      ...mapGetters(["bigsum"])
    }
    ,
    

vuex的mapState,mapGetters,mapActions,mapMutations与模块化_第2张图片

mapActions和mapMutations

  • mapMutations可以生成$store.commit

  • 使用方法为…mapMutations({‘函数名’:‘Mutations里对应函数名字’})(对象形式写法)

  • …mapMutations([‘chu’])(数组形式写法)

  • 使用时注意函数名要传参

  • 借助mapMutation生成对应方法,方法中会调用commit去联系Mutations

  • mapActions和mapMutations用法基本相同

  • 借助mapActions生成对应方法,方法中会调用dispatch去联系Actions

    ...mapMutations({'chu':'CHU'})
    
    ====>>>>>>
    
    chu(){
        this.$store.commit('CHU',this.number)
      }
    
  • mapActions和mapMutations使用时,如果需要传递参数,要在模板中绑定事件是传递好参数,否则参数是事件对象

vuex的mapState,mapGetters,mapActions,mapMutations与模块化_第3张图片


<template>
  <div >
      <div>{{sum}}</div>
      <div>{{$store.getters.bigsum}}</div>
      <select v-model.number="number">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
      <button @click="jia(number)">+++++++++</button>
      <button @click="jian(number)">---------</button>
      <button @click="cheng(number)">******</button>
      <button @click="CHU(number)">//
  </div>
</template>
<script>
import {mapState,mapGetters, mapMutations,mapActions} from 'vuex'
export default {
name:'Count',
data() {
  return {
    
    number:1
  }
},
computed:{
  s(){return 500},
  ...mapState({sum1:"sum"}),
  ...mapState(["sum"]),
  ...mapGetters({bigsum1:"bigsum"}),
  ...mapGetters(["bigsum"])
}
,
methods:{
  // add(){
    
  //   this.$store.dispatch('jia',this.number)
  // },
  // jian(){
  //   this.$store.dispatch("jian",this.number)
  // },
  // cheng(){
  //   this.$store.dispatch("cheng",this.number)
  // },
  ...mapActions(['jia','jian','cheng']),
  // CHU(){
  //   this.$store.commit('CHU',this.number)
  // },
  ...mapMutations(['CHU'])
}
}
</script>

<style>

</style>

多组件数据共享

APP Components

<template>
  <div >
    <Count ref='ccc' />
    <hello/>
  </div>
</template>
<script>
import Count from "./components/Count.vue"
import hello from "./components/hello.vue"
export default {
  name:"App",
  components:{
    Count,hello
  },
  mounted() {
    this.$refs.ccc.$on("hello",()=>{
      console.log("hello,word");
    })
  },
  }
</script>
<style>

</style>
HELLO components
<template>
    <div v-if="sum%2">
        
        <h1> hello {{sum}}</h1>
        <h1>人员列表</h1>
        <ul>
            <input type="text" v-model="name">
            <button @click="add">添加</button>
            <li v-for="p  in person " :key="p.id">{{p.name}}
            </li>
        </ul>
    </div>
</template>
<script>
import {mapState} from 'vuex'
export default {
    data() {
        return {
            name:""
        }
    },
    computed:{
        ...mapState(['sum','person'])
    },
    methods: {
        add(){
            this.$store.commit('add',this.name)
            this.name=''
        }
    },
}
</script>
<style>

</style>
COUNT component

<template>
  <div >
      <div>{{sum}}</div>
      <div>{{$store.getters.bigsum}}</div>
      <select v-model.number="number">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
      <button @click="jia(number)">+++++++++</button>
      <button @click="jian(number)">---------</button>
      <button @click="cheng(number)">******</button>
      <button @click="CHU(number)">//
      <h1>总人数为{{person.length}}</h1>
  </div>
</template>
<script>
import {mapState,mapGetters, mapMutations,mapActions} from 'vuex'
export default {
name:'Count',
data() {
  return {
    
    number:1
  }
},
computed:{
  s(){return 500},
  ...mapState({sum1:"sum"}),
  ...mapState(["sum",'person']),
  ...mapGetters({bigsum1:"bigsum"}),
  ...mapGetters(["bigsum"])
}
,
methods:{
  // add(){
    
  //   this.$store.dispatch('jia',this.number)
  // },
  // jian(){
  //   this.$store.dispatch("jian",this.number)
  // },
  // cheng(){
  //   this.$store.dispatch("cheng",this.number)
  // },
  ...mapActions(['jia','jian','cheng']),
  // CHU(){
  //   this.$store.commit('CHU',this.number)
  // },
  ...mapMutations(['CHU'])
}
}
</script>

<style>

</style>
main.js
// 该文件是整个项目入口文件
// 引入Vue
import Vue from 'vue'
// 引入App组件,他是所有组件的父组件
import App from './App.vue'
import store from './store'
// 关闭Vue生产提示
Vue.config.productionTip = false
// 创建Vue实例对象
new Vue({
// 将App组件放入容器中
  render: h => h(App),
  store,
  beforeCreate(){
    Vue.prototype.$bus=this
  },
}).$mount('#app')

Store.js

import Vuex from "vuex"
import Vue from 'vue'
import {nanoid} from 'nanoid'
Vue.use(Vuex)
const actions={
    jia(context,value){
        console.log(context);
        // console.log(value);
        context.commit("JIA",value)
    },
    jian(context,value){
        context.commit("JIAN",value)
    },
    cheng(context,value){
        setTimeout(() => {
            context.commit('CHENG',value)
        }, 3000);
    },
}
const mutations={
    JIA(state,value){
        state.sum +=value
        console.log(state)
    },
    JIAN(state,value){
        state.sum -=value
    },
    CHENG(state,value){
        state.sum *=value
    },
    CHU(state,value)
    {
        state.sum /=value
    },
    add(state,value){
        state.person.unshift({id:nanoid(),name:value})
    }
    
}
const state={
    sum:0,person:[
    {id:"001",name:"张三"},
    {id:"002",name:"李四"}
]
}
const getters={
    bigsum(state){
        return state.sum*10
    }
}
export default new Vuex.Store({
    // ... 
    actions,mutations,state,getters
})

vuex模块化

vuex的mapState,mapGetters,mapActions,mapMutations与模块化_第4张图片vuex的mapState,mapGetters,mapActions,mapMutations与模块化_第5张图片
vuex的mapState,mapGetters,mapActions,mapMutations与模块化_第6张图片

  • vuex在使用模块化是需要开启命名空间namespace

  • store.js
    
    
    import Vuex from "vuex"
    import Vue from 'vue'
    import {nanoid} from 'nanoid'
    import axios from 'axios'
    Vue.use(Vuex)
    const jisuan={
        namespaced:true,
        actions:{
            jia(context,value){
                console.log(context);
                // console.log(value);
                context.commit("JIA",value)
            },
            jian(context,value){
                context.commit("JIAN",value)
            },
            cheng(context,value){
                setTimeout(() => {
                    context.commit('CHENG',value)
                }, 3000);
            },
        },
        mutations:{
            JIA(state,value){
                state.sum +=value
                console.log(state)
            },
            JIAN(state,value){
                state.sum -=value
            },
            CHENG(state,value){
                state.sum *=value
            },
            CHU(state,value)
            {
                state.sum /=value
            },
        },
        state:{
            sum:0
        },
        getters:{
            bigsum(state){
                return state.sum*10
            }
        }
    }
    const renyuan={
        namespaced:true,
         mutations:{
        add(state,value){
            state.person.unshift({id:nanoid(),name:value})
        }   },
        state:{person:[
        {id:"001",name:"张三"},
        {id:"002",name:"李四"}
    ]
    
        }
    }
    const qingqiu={
        namespaced:true,
        state:{person:[]},
        actions:{
            no1(context,value){
                axios.get(`https://api.github.com/search/users?q=`+value).then(
                response => {
                    console.log("成功",response.data.items);
                    context.commit("NO1",response.data.items)
                },
                error => {
                    console.log("失败",error.message);
                })
    
            }
        },
        mutations:{
            NO1(state,value){
                state.person.unshift(value)
            }
        }
    }
    
    
    export default new Vuex.Store({
        // ... 
        modules:{
            jisuan,renyuan,qingqiu
        }
    })
    
    
    count component
    <template>
      <div >
          <div>{{sum}}</div>
          <div>{{bigsum}}</div>
          <select v-model.number="number">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
          </select>
          <button @click="jia(number)">+++++++++</button>
          <button @click="jian(number)">---------</button>
          <button @click="cheng(number)">******</button>
          <button @click="CHU(number)">//
          <h1>总人数为{{person.length}}</h1>
      </div>
    </template>
    <script>
    import {mapState,mapGetters, mapMutations,mapActions} from 'vuex'
    export default {
    name:'Count',
    data() {
      return {
        
        number:1
      }
    },
    computed:{
      s(){return 500},
      ...mapState('jisuan',["sum"]),
      ...mapState("renyuan",['person']),
      ...mapGetters('jisuan',["bigsum"])
    }
    ,
    methods:{
      // add(){
        
      //   this.$store.dispatch('jia',this.number)
      // },
      // jian(){
      //   this.$store.dispatch("jian",this.number)
      // },
      // cheng(){
      //   this.$store.dispatch("cheng",this.number)
      // },
      ...mapActions('jisuan',['jia','jian','cheng']),
      // CHU(){
      //   this.$store.commit('CHU',this.number)
      // },
      ...mapMutations('jisuan',['CHU'])
    },
    mounted(){
      console.log(this.$store)
    }
    }
    </script>
    
    <style>
    
    </style>
    
    person component
    <template>
      <div>
          ----------------------------------
          <div>
              <input type="text" v-model="name">
              <button @click="no1(name)">按钮</button>
          </div>
          ----------------------------------
      </div>
    </template>
    
    <script>
    import {mapActions} from 'vuex'
    export default {
    data() {
        return {
            name:"",
        }
    },
    methods:{
        ...mapActions("qingqiu",['no1']),
    }
    }
    </script>
    
    <style>
    
    </style>
    
    hello components
    <template>
        <div v-if="sum%2">
            
            <h1> hello {{sum}}</h1>
            <h1>人员列表</h1>
            <ul>
                <input type="text" v-model="name">
                <button @click="add">添加</button>
                <li v-for="p  in person " :key="p.id">{{p.name}}
                </li>
            </ul>
        </div>
    </template>
    <script>
    import {mapState} from 'vuex'
    export default {
        data() {
            return {
                name:""
            }
        },
        computed:{
            ...mapState('jisuan',['sum']),
            ...mapState('renyuan',["person"])
        },
        methods: {
            add(){
                this.$store.commit('renyuan/add',this.name)
                this.name=''
            }
        },
    }
    </script>
    <style>
    
    </style>
    
    APP组件
    
    
    <template>
      <div >
        <Count ref='ccc' />
        <hello/>
        <person/>
      </div>
    </template>
    <script>
    import person from './components/person.vue'
    import Count from "./components/Count.vue"
    import hello from "./components/hello.vue"
    export default {
      name:"App",
      components:{
        Count,hello,person
      },
      mounted() {
        this.$refs.ccc.$on("hello",()=>{
          console.log("hello,word");
        })
      },
      }
    </script>
    <style>
    
    </style>
    

你可能感兴趣的:(vue.js,前端)