Vue插件之vue-resource

admin2024-09-11  24

  • get方式

this.$http.get(‘url’,{

param1:value1,

param2:value2

}).then(function(response){

// response.data中获取ResponseData实体

},function(error){

// 发生错误

});

  • post方式

this.$http.post(‘url’,{

param1:value1,

param2:value2

},{

emulateJSON:true

}).then(function(response){

// response.data中获取ResponseData实体

},function(response){

// 发生错误

});

步骤:

  1. 安装vue-resource模块:cnpm install vue-resource --save

  2. 在main.js中引入vue-resource并通过命令Vue.user()使用该插件

  3. 在组件里面通过get()方法使用

示例:普通请求


  • 服务器端代码:

@WebServlet(urlPatterns = “/servlet/vue”)

public class VueServlet extends javax.servlet.http.HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

doGet(request,response);

}

protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

response.setCharacterEncoding(“UTF-8”);

response.setContentType(“application/json; charset=utf-8”);

response.setHeader(“Access-Control-Allow-Origin”, “*”); //跨域请求

PrintWriter out = response.getWriter();

List userList = new ArrayList<>();

userList.add(new User(11,“zhangsan”,‘女’));

userList.add(new User(22,“lisi”,‘女’));

userList.add(new User(33,“wanger”,‘女’));

userList.add(new User(44,“mazi”,‘男’));

String json = new Gson().toJson(userList);

System.out.println("json "+json);

out.write(json);

}

}

  • 前端代码

第一步:安装vue-resource模块,代码如下:

第二步:在main.js中引入vue-resource并通过命令Vue.user()使用该插件

第三步:页面

<button @click=“getData()”>请求数据

    • {{item}}
    • 示例:


      • 服务器端代码:

      @WebServlet(urlPatterns = “/servlet/vue”)

      public class VueServlet extends HttpServlet {

      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      doGet(request, response);

      }

      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      response.setCharacterEncoding(“UTF-8”);

      response.setContentType(“application/json; charset=utf-8”);

      String callback = request.getParameter(“callback”);

      PrintWriter out = response.getWriter();

      List userList = new ArrayList<>();

      userList.add(new User(11, “zhangsan”, ‘女’));

      userList.add(new User(22, “lisi”, ‘女’));

      userList.add(new User(33, “wanger”, ‘女’));

      userList.add(new User(44, “mazi”, ‘男’));

      String json = new Gson().toJson(userList);

      System.out.println("json " + json);

      out.write(callback + “(” + json + “)”);

      }

      }

    本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!