【问题标题】:How to pass data with specific ID to backend route param?如何将具有特定 ID 的数据传递给后端路由参数?
【发布时间】:2021-04-07 08:31:38
【问题描述】:

我想使用当前 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}}

【问题讨论】:

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


    【解决方案1】:

    Vuex 的主要优点之一是能够在一个组件中设置状态并从另一个组件中获取状态。在另一个组件中,设置一些状态,如state.id。然后您可以将该 id 传递给操作,或者从操作内部的state 获取它。

    这是一个传递它的例子:

    方法

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

    Vuex 操作始终只提供 2 个参数,一个用于上下文对象(包含 commitdispatch 等)和有效负载。将您的操作更改为:

    动作

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

    如果您愿意,可以destructure 有效载荷参数并使用spread operatorid 与其余部分分开:

    动作

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

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

    动作

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 2016-09-21
      • 2023-03-20
      • 2018-06-20
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多