简体   繁体   English

我想从 vuejs 的后端获取用户名

[英]i want to get username from back-end in vuejs

here whare i pass sender id to the server, and get correct name在这里,我将发件人 ID 传递给服务器,并获得正确的名称

nameOfSender(from, to) {
      if (from._id == localStorage.getItem('userID')) {
      return  axios
        .post(
          "http://localhost:3000/get-user-name",
          { to },
          {
            headers: {
              authorization: localStorage.getItem("token"),
            },
          }
        )
        .then((res) => {
          console.log('Chat USer', res.data.name)
          return {
            from: 'you',
            to: res.data.name
        }
        });

and here where i call the method but does not show the name在这里我调用该方法但不显示名称

<v-list-item-title v-text="nameOfSender(chat.from, chat.to).from"></v-list-item-title>
<v-list-item-title v-text="nameOfSender(chat.from, chat.to).to"></v-list-item-title>

As far as I know, axios returns a Promise.据我所知,axios 返回 Promise。 So this kind of access nameOfSender(chat.from, chat.to).from" should not be possible (since it is an asynchronous operation).所以这种访问nameOfSender(chat.from, chat.to).from"应该是不可能的(因为是异步操作)。

A possible solution would be:一个可能的解决方案是:

  data: () => ({
    nameOfSender: {
      from: undefined,
      to: undefined,
    },
  }),
  // ...
  methods: {
    getNameOfSender(from, to) {
      if (from._id == localStorage.getItem('userID')) {
        axios.post("http://localhost:3000/get-user-name",
          { to },
          {
            headers: {
              authorization: localStorage.getItem("token"),
            },
          }
        )
        .then((res) => {
          console.log('Chat USer', res.data.name)
          this.nameOfSender = {
            from: 'you',
            to: res.data.name
          }
        });
        
      }
    }
  },
  mounted() {
    this.getNameOfSender(this.chat.from, this.chat.to);
  }

And then you would be able to access the data by:然后您将能够通过以下方式访问数据:

<v-list-item-title v-text="nameOfSender.from"></v-list-item-title>
<v-list-item-title v-text="nameOfSender.to"></v-list-item-title>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM