美文网首页
Vuex使用

Vuex使用

作者: 程序员不务正业 | 来源:发表于2018-08-25 13:59 被阅读21次
// 遵从store基本写法

// 数据
const state = {};
// 协调回调action
const mutations = {};
// 外部直接调用的方法
const actions = {};
export default {
  state,
  mutations,
  actions
};

其中mutations和actions相互对应,使用:

const state = {
  skip: 0,
  events: []
};
// mutations与actions方法互相对应
// 协调回调action
const mutations = {
  loadMore(state, payload) {
    state.skip += 10;
    state.events = state.events.concat(payload.res);
  }
};
// 外部直接调用的方法
const actions = {
  loadMore({ commit, state }) {
    request({
      url: "event/list?loc=108288&start=1" + state.skip + "&count=10",
      methods: "get",
      params: ""
    })
      .then(function(response) {
        console.log(response);
        commit({
          type: "loadMore",
          res: res.body.events
        });
      })
      .catch(function(error) {})
  }
};

vue文件中处理方法mapActions与mapState中接收后映射

vue中使用对应的数据

<script>
import { mapState, mapActions } from "vuex";
import newsList from "../components/newList";
export default {
  name: "News",
  computed: {
    ...mapState({
      hotMovies: state => state.news.hotMovies,
      topMovies: state => state.news.topMovies,
      newMovies: state => state.news.newMovies,
      movieTags: state => state.news.movieTags
    })
  },
  components: {
    newsList: newsList
  },

  methods: {
    getMovie() {
      this.$store.dispatch("getMovie");
    },
    ...mapActions["getMovie"]
  },
  created() {
    // this.getMovie();
  }
};
</script>

store中参数传递

//参数发送
 methods: {
        getMoreMovie() {
            this.$store.dispatch({
                type: "getMoreMovie",
                moviesType: this.moviesType
            });
        },
        ...mapActions["getMoreMovie"]
    }

//js中参数接收
getMoreMovie({ commit, state }, { moviesType }) {
switch (moviesType) {
      case "1": {
        moreUrl = "/movie/in_theaters?count=8";
        break;
      }
      case "2": {
        moreUrl = "/movie/coming_soon?count=8";
        break;
      }
      case "3": {
        moreUrl = "/movie/top250?count=8";
        break;
      }
    }
}

注意vuex只适合:响应式的状态存储
部分网络请求并不适合vuex,如:提交操作的网络请求

相关文章

网友评论

      本文标题:Vuex使用

      本文链接:https://www.haomeiwen.com/subject/isaavftx.html