添加到数据后,Vue不会渲染我的PK

时间:2019-09-24 03:29:48

标签: vue.js axios vuex

在插入数据时,我在发送pk时遇到问题。我还将使用pk删除条目。

<template>
  <div class="hello">
    <p>Username</p>
    <input type="text" v-model="users_name">
    <p>Mac Address</p>
    <input type="text" v-model="msgBody">
    <br><br>
    <input 
      type="submit" 
      value="Add" 
      @click="addMaclist({ users_name: users_name, mac_id: msgBody })" 
      :disabled="!users_name || !msgBody">

    <hr/>
    <h3>Mac Address on Database</h3>
    <p v-if="maclists.length === 0">No Maclists</p>
    <ul>
    <li v-for="(users, index) in maclists" :key="index">
    <p>{{ index }}</p>
    <p v-html="users.users_name"></p>
    <p v-html="users.msgBody"></p>
    <input type="submit" @click="deleteMaclist(users.pk)" value="Delete" />
    </li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  name: "Maclists",
  data() {
    return {
      users_name: "",
      msgBody: "",
    };
  },
  computed: mapState({
    maclists: state => state.maclists.maclists
  }),
  methods: mapActions('maclists', [
    'addMaclist',
    'deleteMaclist'
  ]),
  created() {
    this.$store.dispatch('maclists/getMaclists')
  }
};
</script>

这是我的json休息区

[
    {
        "url": "http://127.0.0.1:8000/api/maclist/24/",
        "users_name": "test1",
        "mac_id": "test1",
        "pk": 24
    }
]

下面的addMaclist和deleteMaclist模块。

import maclistService from '../../services/maclistService'

const state = {
  maclists: []
}

const getters = {
  maclists: state => {
    return state.maclists
  }
}

const actions = {
  getMaclists ({ commit }) {
    maclistService.fetchMaclists()
    .then(maclists => {
      commit('setMaclists', maclists)
    })
  },
  addMaclist({ commit }, maclist) {
    maclistService.postMaclist(maclist)
    .then(() => {
      commit('addMaclist', maclist)
    })
  },
  deleteMaclist( { commit }, msgId) {
    maclistService.deleteMaclist(msgId)
    commit('deleteMaclist', msgId)
  }
}

const mutations = {
  setMaclists (state, maclists) {
    state.maclists = maclists
  },
  addMaclist(state, maclist) {
    state.maclists.push(maclist)
  },
  deleteMaclist(state, msgId) {
    state.maclists = state.maclists.filter(obj => obj.pk !== msgId)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

这是删除后找不到pk的错误

  

删除http://localhost:8080/api/maclist/undefined/ 404(未找到)

但是如果我在执行删除按钮之前手动刷新页面,它将能够找到pk

1 个答案:

答案 0 :(得分:1)

我只能假定您正在尝试删除刚刚添加的条目。您的问题出在您的addMaclist行动中...

addMaclist({ commit }, maclist) {
  maclistService.postMaclist(maclist)
    .then(() => {
      commit('addMaclist', maclist)
    })
}

当您提交maclist时,这是从组件发送的相同对象,只具有这些属性...

{ users_name: users_name, mac_id: msgBody }

如果您的REST API制作精良,并使用新持久的模型做出响应,那么您应该可以使用它

addMaclist({ commit }, maclist) {
  maclistService.postMaclist(maclist)
    .then(model => {
      commit('addMaclist', model) // add the model from the response
    })
}