How to write a property in the link?

I am new to Vue.js and do a task in which I need to write a property to a link, but I don’t know how to do it? How do I write "counter" from "data" to a link so that it works.

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
    })
  }
}

2 answers

  • answered 2019-03-13 19:13 DjSh

    You need to use Template literals and they "are string literals allowing embedded expressions" so as suggested by others, instead of using a " or ' use (backtick or `) see more here: Template literals. Moreover by using this you can access the variable so:

    created(){
      axios.get(`http://jsonplaceholder.typicode.com/posts?_start=${this.counter}+0&_limit=10`).then(response => {
        this.posts = response.data
      })
    },
    

  • answered 2019-03-14 07:22 Lupu Ștefan Alex

    Axios allows you to add URL query parameters as an object:

    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)
      })
    

    This will yield the same result but it looks a bit more elegant and easier to maintain once you have a lot of parameters in your URLs 😊

    I keep this axios cheat sheet close by for when I'm working with it.