vue.js - vue-router modules设置了命名空间,但是不知道在组件里面如何调用?

查看:228
本文介绍了vue.js - vue-router modules设置了命名空间,但是不知道在组件里面如何调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

// types.js

// 定义 getter、action、和 mutation 的名称为常量,以模块名 `todos` 为前缀
export const DONE_COUNT = 'todos/DONE_COUNT'
export const FETCH_ALL = 'todos/FETCH_ALL'
export const TOGGLE_DONE = 'todos/TOGGLE_DONE'
// modules/todos.js
import * as types from '../types'

// 使用添加了前缀的名称定义 getter、action 和 mutation
const todosModule = {
  state: { todos: [] },

  getters: {
    [types.DONE_COUNT] (state) {
      // ...
    }
  },

  actions: {
    [types.FETCH_ALL] (context, payload) {
      // ...
    }
  },

  mutations: {
    [types.TOGGLE_DONE] (state, payload) {
      // ...
    }
  }
}

现在我在组件有这样的代码

  import { mapActions } from 'vuex'

 methods:{
      ...mapActions([
        types.FETCH_ALL
      ]),
      getAction(){
         //todo:我这里调用上面的types.FETCH_ALL怎么调呢?用this.types.FETCH_ALL我试了是不对的!!!
      }
      }

看来mapActions 需要先在根节点注入 store,不能注入modules文件里面,哎!!!

解决方案

types.js是个文件,

  ...mapActions([
        types.FETCH_ALL//映射this['todos/FETCH_ALL']()为this.$store.dispatch('todos/FETCH_ALL'),
      ]),

在另外一个文件使用的话肯定要引入的,然后你要知道mapActions的作用是什么,

getAction(){
    this['todos/FETCH_ALL']();//这么触发action就行了
}

多去看看官网和github上的examples

store/index.js

import Vue from 'vue';
import Vuex from 'vuex'
import * as actions from './actions.js'
import * as getters from './getters'
import cart from './modules/cart'
// import products from './modules/products'

Vue.use(Vuex);

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
  actions,
  getters,
  modules: {
    cart
  },
  strict: debug,
});

store/modules/cart.js

import * as types from '../mutation-types'

// initial state
// shape: [{ id, quantity }]
const state = {
  added: [],
  checkoutStatus: null
}

// getters
const getters = {
  checkoutStatus: state => state.checkoutStatus
}

// actions
const actions = {
  checkout({ commit, state }, { id }) {
    console.info("actions", id);
    commit(types.CHECKOUT_REQUEST, { id });
  }
}

// mutations
const mutations = {
  [types.CHECKOUT_REQUEST](state, { id }) {
    // clear cart
    console.info("mutations", id);
    state.added = []
    state.checkoutStatus = null
  },
  [types.ADD_TO_CART](state, { id }) {
    state.lastCheckout = null
    const record = state.added.find(p => p.id === id)
    if (!record) {
      state.added.push({
        id,
        quantity: 1
      })
    } else {
      record.quantity++
    }
  },
}

export default {
  state,
  getters,
  actions,
  mutations
}

main.js

import Vue from 'vue'
import store from './store'
import App from './App'
import router from './router'

new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})

这篇关于vue.js - vue-router modules设置了命名空间,但是不知道在组件里面如何调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆