vuex-学习

62 阅读1分钟
70~end,vuex/跨域
v3-cli的跨域配置,actions的用法
vue.config.js中:
devServer: {
    proxy: {
        '/path': {
            target'https://i.maoyan.com',
            changeOrigintrue// 开启代理
            pathRewrite: {
                '^/path'''
            }
        }
    }
},
store中:
state() {
    return {
        list: [],
    };
},
actions: {
    getHot(context) { // context:与store实例具有相同的属性和方法的对象
        fetch("/path/api/mmdb/movie/v3/list/hot.json?ct=成都&ci=59&channelId=4")
            .then((res) => {
                return res.json();
            })
            .then((res) => {
                context.commit("changeList", res.data.hot);
                console.log(context.state.list, 1);
            });
    },
},
辅助函数

mapState/mapMutations/mapGetters/mapActions

嫌store.state.num,store.commit('updateNum',1);太麻烦了?

{{num}}
<button @click="click">改变num</button>
{{ forNum }}
import { mapState,mapMutations,mapGetters, mapActions } from "vuex";
computed: {
    // ...mapState(['num','list']) // 第一种写法:数组形式
    ...mapState({
      // num:'num' // 第二种写法
      list: (state) => state.list, // 第三种写法
    }),
    ...mapGetters(["forNum"]),
},
methods:{
    ...mapMutations(['changeNum']),
    ...mapActions(['getHot']),
    click(){
      this.changeNum(2)
    }
},
mounted() {
    this.getHot();
},
模块化module

使用:

store下新建user,user中:
const moduleA = {
    state() {
        return {
            userA: '小白',
            age: 18,
        }
    },
    getters: {
        forAge(state) {
            return '00' + state.age
        }
    },
    mutations: {
        changeAge(state) {
            state.age += 1
        },

    },
}
export default moduleA

store中:
import user from './user'
export default createStore({
    modules: {
        a: moduleA,
    },
});

home中:
{{ $store.state.a.userA }} // state:$store.state.模块名.userA使用
{{$store.getters.forAge}} // getters:$store.getters.forAge使用
// mutations,actions:$store.commit.函数名使用
<button @click="$store.commit('changeAge')">改变age</button>

局部访问全局的state/getters:

参数getters可以直接访问所有的getters,参数rootState可以访问全局的state
!actions中也有第三个参数rootState,详见官方文档
getters: {
    forAge(state, getters, rootState) {
        console.log(getters, 1);
        console.log(rootState, 2);
        return '00' + state.age
    }
},
命名空间

getters/mutations/actions其实本质上还是全局的,怎么改为局部写法呢?

user中:
const user = {
    namespaced: true, // 注意不是namespace!
    ...
}

home中:
{{ $store.state.a.userA }} // state不变
{{$store.getters['a/forAge']}} // getters
<button @click="$store.commit('a/changeAge')">改变age</button> // mutations

在命名空间中使用辅助函数

home中:
{{userA}}
{{forAge}}
<button @click="changeAge">改变age</button>
computed: {
    ...mapState('a',['userA']),
    ...mapGetters('a',['forAge'])

},
methods: {
    ...mapMutations('a',['changeAge'])
},