【问题标题】:calling Axios api with ${item} in the url在 url 中使用 ${item} 调用 Axios api
【发布时间】:2020-09-03 17:02:18
【问题描述】:

我无法在 Vuetify 上调用 axios,因为 URL 中有反引号和 ${}。我想我想把它变成 JSON,所以我试过了,但它不起作用。你能给我解释一下吗?

下面是我的代码。当我按下Search 按钮时,控制台会说:

[Vue warn]: Error in v-on handler: 'ReferenceError: term is not defined'
<div id="app">
  <v-app >
    <v-form >
      <v-row class="app">
        <v-col class="text-center" cols="12" sm="4">
             <v-text-field
              placeholder="Find Book"
            ></v-text-field>
          <div class="my-2">
            <v-btn v-on:click="getBooks" large color="primary">Search</v-btn>
          </div>
        </v-col>
      </v-row>
      </v-form>
  </v-app>
  <!-- You may use this container for your listing -->
  <div>
    
  </div>
</div>
new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  
  components: {},
  data(){
    return{
      books: []
    }
  },
  methods: {
    getBooks: function() {
      const apiUrl = `https://goodreads-server-express--dotdash.repl.co/search/${term}`;
      const obj = JSON.parse(apiUrl)
 
      axios.get("obj")
        .then(function (resp) {
        this.books = resp.data
        console.log(this.books)
      })
    },
  }    
});

【问题讨论】:

    标签: javascript vue.js axios vuetify.js


    【解决方案1】:

    Template literals(反引号字符串)支持占位符(${term} 部分),它可以包含表达式,或者在这种情况下是一个变量。 ${term} 抛出错误,因为当前作用域中没有名为“term”的变量。

    您也不需要在apiUrl 上使用JSON.parse(),因为apiUrl 不是JSON。而是将apiUrl 直接传递给axios.get()

    const term = 'Moby Dick';
    const apiUrl = `https://goodreads-server-express--dotdash.repl.co/search/${term}`;
    axios.get(apiUrl).then(...)
    

    new Vue({
      el: '#app',
      data: () => ({
        books: [],
      }),
      methods: {
        getBooks() {
          const term = 'Moby Dick'
          const apiUrl = `https://goodreads-server-express--dotdash.repl.co/search/${term}`
          axios.get(apiUrl).then(resp => {
            this.books = resp.data
          })
        }
      }
    })
    <script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
    <script src="https://unpkg.com/axios@0.20.0/dist/axios.min.js"></script>
    
    <div id="app">
      <button @click="getBooks">Get books</button>
      <pre>{{ books }}</pre>
    </div>

    【讨论】:

    • 感谢您的回复。快速提问..所以如果我需要输入来进入术语..那么我可以在 data() 和 vmodel 中添加 search: ' ' 并将您的 const 术语更改为 const term = this .搜索
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2016-07-21
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    相关资源
    最近更新 更多