vue - 优化vuex
computed属性中
mapState 映射state:
<template> <div> {{name}} </div> </template> <script> //引入mapState import {mapState} from 'vuex' export default { name: 'Human', computed: { //之前的写法 /*getName(){ return this.$store.state.name },*/ //这种写法更方便 //对象写法 ...mapState({name: 'name',balance: 'balance',bodyObj: 'bodyObj'}), //数组写法 ...mapState(['name','balance','bodyObj']) } } </script>
mapGetter映射getters:
<template> <div> {{bigValue}} </div> </template> <script> //引入mapGetters import {mapGetters} from 'vuex' export default { name: 'Human', computed: { //对象写法 ...mapGetters({bigValue: 'bigValue'}), //数组写法 ...mapGetters(['bigValue']) } } </script>
methods属性中
mapMutations 映射:
<template> <div> {{this.$store.state.name}} <!--必须指定参数(这个name在data中),不然value就是event或者为空(不是点击事件调用)--> <button @click="setName(name)">修改</button> </div> </template> <script> //引入mapMutations import {mapMutations} from 'vuex' export default { data(){ return { name: 'mkasas' } }, name: 'Human', methods: { //对象写法 ...mapMutations({setName: 'SETNAME'}), //数组写法 ...mapMutations(['SETNAME']) } } </script>
mapActions映射:
<template> <div> {{this.$store.state.name}} <!--必须指定参数(这个name在data中),不然value就是event或者为空(不是点击事件调用)--> <button @click="setName(name)">修改</button> </div> </template> <script> //引入mapActions import {mapActions} from 'vuex' export default { data(){ return { name: 'mkasas' } }, name: 'Human', methods: { //对象写法 ...mapActions({setName: 'setName'}), //数组写法 ...mapActions(['setName']) } } </script>
mapActions