【问题标题】:How call out queries through axios in Vue JsVue Js中如何通过axios调出查询
【发布时间】:2017-10-19 18:43:45
【问题描述】:

我正在尝试使用类似这样的 url 调用查询搜索:

http://localhost/Stellar/public/api/companies?column=name&direction=desc&page=1

在 Vue Js 2.0 中尝试这样调用:

axios.get('$(this.source)?column=$(this.query.column)&direction=$(this.query.direction)$page=$(this.query.page)')

它看起来像这样

http://localhost/Stellar/public/$(this.source)?column=$(this.query.column)&direction=$(this.query.direction)$page=$(this.query.page)

它没有转换数据。帮我解决这个问题。

谢谢。

【问题讨论】:

    标签: javascript vue.js vuejs2 axios


    【解决方案1】:

    当您将变量明确写在字符串中时,您并没有引用它们。

    做这样的事情:

    let source = this.source;
    let column = this.query.column;
    let direction = this.query.direction;
    let page = this.query.page;
    
    axios.get(source+"?column="+column+"&direction="+direction+"&page="+page);
    

    【讨论】:

      【解决方案2】:

      您需要使用字符串插值。它是这样的:

      let variable = 'dog';
      
      let string = `This is a string using string interpolation. The variable is: ${variable}`;
      
      console.log(string);

      它的要点是你需要用`包围字符串,变量需要用${}包裹。因此,对于您的示例,它应该使用:

      axios.get(`${$(this.source)}?column=${$(this.query.column)}&direction=${$(this.query.direction)}&page=${$(this.query.page)}`);
      

      顺便说一句,我替换了 'page=' 之前的 '$' 符号,因为这对我来说似乎是一个错误。如果不是,请注意我更改了它。

      edit:我还假设当您使用 $(this.query) 等时,您正在调用 jQuery。也有可能您只是错误地使用了字符串插值,因此需要将括号替换为 {}。

      【讨论】:

        【解决方案3】:

        首先构建字符串。如果您将变量放入字符串中(您的 axios 调用的第一个参数)......在 javascript 中,这些变量不会计算。

        let dest = this.source+'?column='+this.query.column+'&direction='+this.query.direction+'&page='+this.query.page;
        
        axios.get(dest).then(response=>{
          console.log(response.data);
        });
        

        进一步阅读:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String

        【讨论】:

          【解决方案4】:

          Axios 请求配置有一种更优雅的方式:

          const url = "mysite.com";
          const config = {
             params: {
                 column: 42,
                 direction: 'up'
              }
          }
          return axios.get(url, config)
             .then((response) => { 
                  ...
          

          【讨论】:

            猜你喜欢
            • 2021-10-05
            • 2019-07-10
            • 2018-12-12
            • 1970-01-01
            • 2020-11-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-04-03
            相关资源
            最近更新 更多