如何将具有特定 ID 的数据传递给后端路由参数?

时间:2020-12-30 21:17:52

标签: javascript vue.js vuejs2 vue-component vuex

我想使用当前 ID 向后端路由参数发布消息。 我如何让系统知道我正在传递这个 ID?

Vuex 动作:

postMessage({commit}, payload, id) {
  axios.post(`http://localhost:5000/channels/${id}/messages` ,payload)
    .then((res) => {
      commit(SET_POSTS, res.data)
    })
}

这是发布操作,但我需要以某种方式传递当前频道 ID。但是频道 ID 在不同的组件中?

postMessage() {
  const postData = {
    description: this.description,
    timestamp: this.timestamp
  };
  this.$store.dispatch("postMessage", postData)
},

在另一个组件中,我的侧边菜单中有一个频道列表,例如不和谐,我像这样显示

 p.d-flex.align-items-center.channel-item(v-for="channel in channelName" :key="channel.id")
      strong.hash.mr-3 #
      | {{channel.channel_name}}

1 个答案:

答案 0 :(得分:1)

Vuex 的主要好处之一是能够在一个组件中设置状态并从另一个组件中获取状态。在另一个组件中,设置一些状态,如 import {ConnectionOptions} from "typeorm"; import path from "path"; const isCompiled = path.extname(__filename).includes('js'); const fileExtension = isCompiled ? "js" : "ts"; export default { type: "postgres", host: process.env.DB_HOST || "localhost", port: Number(process.env.DB_PORT) || 5432, username: process.env.DB_USERNAME || "test", password: process.env.DB_PASSWORD || "test", database: process.env.DB_NAME || "test", synchronize: true, logging: false, entities: [ `src/business/**/*.entity.${fileExtension}` ], migrations: [ `src/migration/**/*.${fileExtension}` ], subscribers: [ `src/subscriber/**/*.${fileExtension}` ] } as ConnectionOptions; 。然后,您可以将该 ID 传递给操作,也可以从操作内的 state.id 获取它。

这是一个传递它的例子:

方法

state

Vuex 操作始终仅提供 2 个参数,一个用于上下文对象(包含 postMessage() { const postData = { id: this.$store.state.id, description: this.description, timestamp: this.timestamp }; this.$store.dispatch("postMessage", postData) } commit 等)和有效负载。将您的操作更改为:

操作

dispatch

如果您愿意,您可以 destructure 有效载荷参数并使用 spread operatorpostMessage({ commit }, payload) { axios.post(`http://localhost:5000/channels/${payload.id}/messages`, payload) .then((res) => { commit(SET_POSTS, res.data) }) } 与其余部分分开:

操作

id

您也可以将 id 排除在有效负载之外,并直接从操作中的状态获取它:

操作

postMessage({ commit }, { id, ...payload }) {
  axios.post(`http://localhost:5000/channels/${id}/messages`, payload)
    .then((res) => {
      commit(SET_POSTS, res.data)
    })
}