Importing methods that return data in Vue/Vuetify 3 and updating tables axios.

huangapple go评论67阅读模式
英文:

Importing methods that return data in Vue/Vuetify 3 and updating tables axios

问题

以下是您要翻译的内容:

"Currently using Vuetify 3 I'm trying to get this search method 'showBills' to return data to the search page, and then update the search page to display the fetched data.

I have already tested these things and they are working:

  • API URI string with search results: returns data when used in a browser
  • Method: when written directly as part of the search page before being included in another js file that is imported would populate page with data fetched from API, now that it's exported, will populate an alert with JSON data
  • Method import: method is properly called and will pop up alert boxes with dummy text and API returned text when called from another js file

My guess is that it has something to do with the way I'm either rendering/handling page updates or the way that I am returning data from the method

Any insight?

This is the search page

<template>
  <v-text-field
    v-model="keywords"
    :loading="loading"
    density="compact"
    clearable
    label="Keyword"
    variant="outlined"
    hint="Keywords are words that might be in the bill"
    prepend-inner-icon="mdi-magnify"
    single-line
    hide-details
    @keydown.enter.prevent="$bills = showBills(keywords)"
  ></v-text-field>
  <v-table>
    <thead>
      <tr>
        <th class="text-left">BILL ID</th>
        <th class="text-left">BILL NUMBER</th>
        <th class="text-left">TITLE</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="bill in bills" v-bind:key="bill.bill_id">
        <td>{{ bill.bill_id }}</td>
        <td>{{ bill.bill_number }}</td>
        <td>{{ bill.title }}</td>
      </tr>
    </tbody>
  </v-table>
</template>
<script>
import { showBills } from '../dir/file.js'
export default {
  name: 'KeywordResults',
  data() {
    return {
      bills: [],
      keywords: []
    }
  },
  methods: {
    showBills
  }
}
</script>

This is the method

import axios from 'axios'
import _ from 'underscore'

export function showBills(keywordString) {
  axios
    .get('api query string', {
      params: {
        key: 'redacted',
        op: 'search',
        state: 'mystate',
        query: keywordString.split().join(',')
      }
    })
    .then((response) => {
      var bills2 = []
      response = response.data.searchresult
      delete response.summary
      _.each(response, function (value) {
        bills2.push(value)
      })
      // In debugging i put alert(bills2) which worked
      // and the alert window showed "[object, object],[object,object],..."
      return bills2
    })
    .catch(() => {
      this.bills2 = []
    })
}
英文:

Currently using Vuetify 3 I'm trying to get this search method "showBills" to return data to the search page, and then update the search page to display the fetched data.

I have already tested these things and they are working:

  • API URI string with search results: returns data when used in a browser
  • Method: when written directly as part of the search page before being included in another js file that is imported would populate page with data fetched from API, now that it's exported, will populate an alert with JSON data
  • Method import: method is properly called and will pop up alert boxes with dummy text and API returned text when called from another js file

My guess is that it has something to do with the way I'm either rendering/handling page updates or the way that I am returning data from the method

Any insight?

This is the search page

&lt;template&gt;
  &lt;v-text-field
    v-model=&quot;keywords&quot;
    :loading=&quot;loading&quot;
    density=&quot;compact&quot;
    clearable
    label=&quot;Keyword&quot;
    variant=&quot;outlined&quot;
    hint=&quot;Keywords are words that might be in the bill&quot;
    prepend-inner-icon=&quot;mdi-magnify&quot;
    single-line
    hide-details
    @keydown.enter.prevent=&quot;$bills = showBills(keywords)&quot;
  &gt;&lt;/v-text-field&gt;
  &lt;v-table&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        &lt;th class=&quot;text-left&quot;&gt;BILL ID&lt;/th&gt;
        &lt;th class=&quot;text-left&quot;&gt;BILL NUMBER&lt;/th&gt;
        &lt;th class=&quot;text-left&quot;&gt;TITLE&lt;/th&gt;
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
      &lt;tr v-for=&quot;bill in bills&quot; v-bind:key=&quot;bill.bill_id&quot;&gt;
        &lt;td&gt;{{ bill.bill_id }}&lt;/td&gt;
        &lt;td&gt;{{ bill.bill_number }}&lt;/td&gt;
        &lt;td&gt;{{ bill.title }}&lt;/td&gt;
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/v-table&gt;
&lt;/template&gt;
&lt;script&gt;
import { showBills } from &#39;../dir/file.js&#39;
export default {
  name: &#39;KeywordResults&#39;,
  data() {
    return {
      bills: [],
      keywords: []
    }
  },
  methods: {
    showBills
  }
}
&lt;/script&gt;

This is the method

import axios from &#39;axios&#39;
import _ from &#39;underscore&#39;

export function showBills(keywordString) {
  axios
    .get(&#39;api query string&#39;, {
      params: {
        key: &#39;redacted&#39;,
        op: &#39;search&#39;,
        state: &#39;mystate&#39;,
        query: keywordString.split().join(&#39;,&#39;)
      }
    })
    .then((response) =&gt; {
      var bills2 = []
      response = response.data.searchresult
      delete response.summary
      _.each(response, function (value) {
        bills2.push(value)
      })
      //In debugging i put alert(bills2) which worked
      //and the alert window showed &quot;[object, object],[object,object],...&quot;
      return bills2
    })
    .catch(() =&gt; {
      this.bills2 = []
    })
}

答案1

得分: 2

以下是翻译好的部分:

这应该可以工作:

外部方法:

export const showBills = (keywords) =>
  axios
    .get('api查询字符串', {
      params: {
        key: '已编辑',
        op: '搜索',
        state: '我的状态',
        query: keywords.split().join(',')
      }
    })
    .then(
      ({
        data: {
          searchresult: { summary, ...result }
        }
      }) => Object.values(result)
    )
    .catch(() => [])

用法:

import { showBills } from './路径到showBills'
export default {
  data: () => ({ bills: [] }),
  methods: {
    async showBills(keywords) {
      this.bills = await showBills(keywords)
    }
  }
}

或者,只需进行最少的更改,在您当前的函数前加上return。还可以在catch中使用return [],而不是分配给未定义的this.bills2

export function showBills(keywordString) {
  return axios
    .get('api查询字符串', {
      params: {
        key: '已编辑',
        op: '搜索',
        state: '我的状态',
        query: keywordString.split().join(',')
      }
    })
    .then((response) => {
      const result = response.data.searchresult
      delete result.summary
      return Object.values(result)
    })
    .catch(() => [])
}

showBills的使用保持不变(如上所示)。

另外,.split().join(',') 不对任何文本进行任何操作。

给定const s = '一些文本's.split()返回['一些文本'],这使得随后的.join(',')是无用的,因为如果输入是一个具有单个元素的数组,那么不会添加逗号。初始字符串将不经修改地发送到后端。

如果它应该返回['一些', '文本'],以便服务器接收'一些,文本',您应该使用s.split(' ').join(',')(或者更好的是s.trim().split(/\s+/).join(','),它将多个空格视为单个空格,并删除任何前导或尾随空格)。

另一个我在您的组件中看到的问题是,您将keywords初始化为空数组,并在<v-text-field>v-model中使用它,而v-model在文本输入上应该是一个字符串。

最后但同样重要的是,我会将方法命名为getBills,而不是showBills,因为这是它的功能。模板*“显示”*它们,一旦该方法填充this.bills

参考:关于解构中未使用变量的eslint的投诉:

  1. 阅读 此链接
  2. 将以下内容添加到您的eslint配置中:
{
  "rules": {
    "no-unused-vars": ["error", { "ignoreRestSiblings": true }]
  }
}

或者,您可以将以下内容放在有问题的行之前:

// eslint-disable-next-line no-unused-vars
英文:

This should work:

The external method:

export const showBills = (keywords) =&gt;
  axios
    .get(&#39;api query string&#39;, {
      params: {
        key: &#39;redacted&#39;,
        op: &#39;search&#39;,
        state: &#39;mystate&#39;,
        query: keywords.split().join(&#39;,&#39;)
      }
    })
    .then(
      ({
        data: {
          searchresult: { summary, ...result }
        }
      }) =&gt; Object.values(result)
    )
    .catch(() =&gt; [])

Usage:

import { showBills } from &#39;./path/to/showBills&#39;
export default {
  data: () =&gt; ({ bills: [] }),
  methods: {
    async showBills(keywords) {
      this.bills = await showBills(keywords)
    }
  }
}

Or, with the least amount of changes, place a return in front of axios in your current function. Also return [] from catch, instead of assigning to an undefined this.bills2:

export function showBills(keywordString) {
  return axios
    .get(&#39;api query string&#39;, {
      params: {
        key: &#39;redacted&#39;,
        op: &#39;search&#39;,
        state: &#39;mystate&#39;,
        query: keywordString.split().join(&#39;,&#39;)
      }
    })
    .then((response) =&gt; {
      const result = response.data.searchresult
      delete result.summary
      return Object.values(result)
    })
    .catch(() =&gt; [])
}

The usage of showBills remains unchanged (as shown above).


Side note: .split().join(&#39;,&#39;) doesn't do anything to any text.

Given const s = &#39;Some text&#39;, s.split() returns [&#39;Some text&#39;], which makes the consequent .join(&#39;,&#39;) useless, as no comma will be added if the input is a an array with a single element. The initial string is sent unchanged to backend.

If it should return [&#39;Some&#39;, &#39;text&#39;], so that the server receives: &#39;Some,text&#39;, you should use s.split(&#39; &#39;).join(&#39;,&#39;) (or, better yet, s.trim().split(/\s+/).join(&#39;,&#39;), which treats multiple spaces as a single one and also removes any leading or trailing spaces).

Another problem I see in your component is that you initialise keywords with an empty array and use it in a &lt;v-text-field&gt;'s v-model, which expects a string. It's possible Vuetify sanitises it behind the scenes, so it works, but v-model on a text input should be a string.

Last, but not least, I'd call the method getBills, not showBills, because that's what it does. The template "shows" them, as soon as the method populates this.bills.


Ref: eslint complaining about unused vars in destructuring:

  1. Read this
  2. Add this to your eslint config:
{
  &quot;rules&quot;: {
    &quot;no-unused-vars&quot;: [&quot;error&quot;, { &quot;ignoreRestSiblings&quot;: true }]
  }
}

Alternatively, you could place this above the offending line:

  // eslint-disable-next-line no-unused-vars

huangapple
  • 本文由 发表于 2023年3月31日 04:06:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定