input 输入框根据关键词查询内容

611 阅读1分钟

后端:

1 引入sql连接 https://juejin.cn/post/6989150498922168334
2 创建接口,接收前端查询的关键字,执行sql语句,将查询结果 res.send给前端
注意:模糊查询sql语句 like这里的各种单引号和双引号不要有空格 否则有异常 无法正确查询所有信息

var connection = require('../sql/sql')
// 创建搜索接口
router.get('/api/goods/shopList', function (req, res, next) {
  // 查看前端给后端传的数据
  console.log(req.query);

  let SearchNames = req.query.searchName;

  // 数据库进行 模糊查询
  connection.query('select * from shoplist where introduce like "%' + SearchNames + '%"', function (err, result) {
    // console.log(result);
    res.send({
      code: 0,
      data: result
    })
  })

})

前端:

1.使用封装好的axios  发送请求,把查询关键字 通过路由传递给后端
注意事项:查询的时候要通过监听url的改变来重新发起请求,否则只能查询一次而已

  methods: {
    async getData() {
      await http
        .$axios({
          url: "/api/goods/shopList",
          params: {
            // 前端给后端传一个数据
            searchName: this.$route.query.key,
          },
        })
        .then((res) => {
          // console.log(res);
          this.shopList = res;
        });
    },
    // 监听路由 如果路由发生改变 就再请求查询一次
  },
  watch: {
    $route() {
      this.getData();
    },
  },