【问题标题】:Vuex - Unknown action type CreateProfile / ProfileListVuex - 未知的操作类型 CreateProfile / ProfileList
【发布时间】:2021-07-22 13:20:48
【问题描述】:

每个人。我有一个简单的项目,我可以在其中创建一个模型并列出它们。 我已经完成了 2 个分别正常工作的项目:

https://github.com/apirobot/django-vue-simplenote

https://github.com/jakemcdermott/vue-django-rest-auth

并将它们与我自己的后端合并在一起,效果也很好。 但我收到Vuex - Unknown action type CreateProfile (on clicking the submit button) / ProfileList (on refreshing) 错误。

src/api/profiles.js

import { HTTP } from './common'
export const Profile = {
  create (config) {
    return HTTP.post('/profiles/', config).then(response => {
      return response.data
    })
  },
  delete (profile) {
    return HTTP.delete(`/profiles/${profile.id}/`)
  },
  list () {
    return HTTP.get('/profiles/').then(response => {
      return response.data
    })
  }
}

src/components/CreateProfile.vue

/* eslint-disable */
<template lang="pug">
  form.form-horizontal(@submit="submitForm")
    .form-group
      .col-3
        label.form-label User
      .col-9
        input.form-input(type="text" v-model="user" placeholder="Type pk...")
    .form-group
      .col-3
        label.form-label Name
      .col-9
        input.form-input(type="text" v-model="name" placeholder="Type profile name...")
    .form-group
      .col-3
        label.form-label Phone number
      .col-9
        textarea.form-input(v-model="phone_number" rows=8 placeholder="Type profile phone number...")
    .form-group
      .col-3
        label.form-label Address
      .col-9
        textarea.form-input(v-model="address" rows=8 placeholder="Type profile address...")    
    .form-group
      .col-3
      .col-9
        button.btn.btn-primary(type="submit") Create
</template>
<script>
export default {
  name: 'create-profile',
  data () {
    return {
      'user': '',
      'name': '',
      'phone_number': '',
      'address': ''
    }
  },
  methods: {
    submitForm (event) {
      this.createProfile()
      // Т.к. мы уже отправили запрос на создание заметки строчкой выше,
      // нам нужно теперь очистить поля title и body
      this.user = ''
      this.name = ''
      this.phone_number = ''
      this.address = ''
      // preventDefault нужно для того, чтобы страница
      // не перезагружалась после нажатия кнопки submit
      event.preventDefault()
    },
    createProfile () {
      // Вызываем действие `createNote` из хранилища, которое
      // отправит запрос на создание новой заметки к нашему API.
      this.$store.dispatch('createProfile', { user: this.user, name: this.name, phone_number: this.phone_number, address: this.address })
    }
  }
}
</script>

src/components/ProfileList.vue

/* eslint-disable */
<template lang="pug">
  #app
    .card(v-for="profile in profiles")
      .card-header
        button.btn.btn-clear.float-right(@click="deleteProfile(profile)")
        .card-title {{ profile.name }}
        
      .card-body {{ profile.phone_number }}
      .card-body {{ profile.address }}
</template>
<script>
import { mapGetters } from 'vuex'
export default {
  name: 'profile-list',
  computed: mapGetters(['profiles']),
  methods: {
    deleteProfile (profile) {
      // Вызываем действие `deleteNote` из нашего хранилища, которое
      // попытается удалить заметку из нашех базы данных, отправив запрос к API
      this.$store.dispatch('deleteProfile', profile)
    }
  },
  beforeMount () {
    // Перед тем как загрузить страницу, нам нужно получить список всех
    // имеющихся заметок. Для этого мы вызываем действие `getNotes` из
    // нашего хранилища
    this.$store.dispatch('getProfiles')
  }
}
</script>
<style>
  header {
    margin-top: 50px;
  }
</style>

存储/index.js

import Vue from 'vue';
import Vuex from 'vuex';
import createLogger from 'vuex/dist/logger';

import auth from './auth';
import password from './password';
import signup from './signup';
import { Profile } from '../api/profiles';
import {
  ADD_PROFILE,
  REMOVE_PROFILE,
  SET_PROFILES
} from './mutation-types.js'

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

Vue.use(Vuex);
const state = {
  profiles: []  // список заметок
}
// Геттеры
const getters = {
  profiles: state => state.profiles  // получаем список заметок из состояния
}
// Мутации
const mutations = {
  // Добавляем заметку в список
  [ADD_PROFILE] (state, profile) {
    state.profiles = [profile, ...state.profiles]
  },
  // Убираем заметку из списка
  [REMOVE_PROFILE] (state, { id }) {
    state.profiles = state.profiles.filter(profile => {
      return profile.id !== id
    })
  },
  // Задаем список заметок
  [SET_PROFILES] (state, { profiles }) {
    state.profiles = profiles
  }
}
// Действия
const actions = {
  createProfile ({ commit }, profileData) {
    Profile.create(profileData).then(profile => {
      commit(ADD_PROFILE, profile)
    })
  },
  deleteProfile ({ commit }, profile) {
    Profile.delete(profile).then(response => {
      commit(REMOVE_PROFILE, profile)
    })
  },
  getProfiles ({ commit }) {
    Profile.list().then(profiles => {
      commit(SET_PROFILES, { profiles })
    })
  }
}

export default new Vuex.Store({
  modules: {
    auth,
    password,
    signup,
    state,
    getters,
    actions,
    mutations
  },
  strict: debug,
  plugins: debug ? [createLogger()] : [],
});

store/mutation-types.js

export const ADD_PROFILE = 'ADD_PROFILE'
export const REMOVE_PROFILE = 'REMOVE_PROFILE'
export const SET_PROFILES = 'SET_PROFILES'

views/CreateProfile.vue 和 views/ProfileList.vue 与 src/components 相同。

谢谢。

【问题讨论】:

  • 在 store/index.js 为什么你的模块对象中有 state/getters/actions?
  • 另一件事是在表单中使用@submit.prevent="",此修饰符会在您提交表单时阻止页面重新加载。
  • 回答问题。这些是在原始项目中并且它们有效,所以我将它们合并在一起,希望它会起作用。请问在哪里,能详细点吗?

标签: vue.js


【解决方案1】:

最后是你的 store/index.js 文件。

应该是这样的。

export default new Vuex.Store({
  modules: {
    auth,
    password,
    signup,
  },
  state,
  getters,
  actions,
  mutations,
  strict: debug,
  plugins: debug ? [createLogger()] : [],
});

您可以将模块视为全新的存储,具有自己的状态、操作、getter 和突变。

【讨论】:

  • 我看到你在 store/inde.js 文件中做了很多“配置文件”的事情,创建一个新模块是一个很好的做法,比如 profile.js 并将其包含为一个模块在根存储中。保持你的根存储尽可能干净
猜你喜欢
  • 2019-03-13
  • 1970-01-01
  • 2021-07-21
  • 2019-10-28
  • 2022-01-02
  • 2021-06-26
  • 2020-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多