首页 > 解决方案 > 如何在链接中写属性?

问题描述

我是 Vue.js 的新手,并且执行一项任务,我需要将属性写入链接,但我不知道该怎么做?如何将“计数器”从“数据”写入链接以使其正常工作。

export default {
  name: 'app',
  data () {
    return {
      counter: 1,
    }
  },
  created(){
    axios.get('http://jsonplaceholder.typicode.com/posts? 
      _start=${counter}+0&_limit=10').then(response => {
      this.posts = response.data
    })
  }
}

标签: javascriptvue.jsaxios

解决方案


Axios 允许您将 URL 查询参数添加为对象:

axios.get('http://jsonplaceholder.typicode.com/posts', {
    params: {
      _start: this.counter, //or `${this.counter}+0` if you need that +0 as a string at the end
      _limit: 10

    }
  })
  .then(function (response) {
    this.posts = response.data
  })
  .catch(function (error) {
    console.log(error)
  })

这将产生相同的结果,但是一旦您的 URL 中有很多参数,它看起来会更优雅且更易于维护

当我使用它时,我将这个 axios 备忘单放在附近。


推荐阅读