SearchBox.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <template>
  2. <!--搜索框-->
  3. <el-autocomplete
  4. v-model="keyword"
  5. :fetch-suggestions="querySearchAsync"
  6. :placeholder="placeholder"
  7. clearable
  8. suffix-icon="el-icon-search"
  9. size="medium"
  10. :debounce="1000"
  11. :style="sw"
  12. @keyup.enter.native="onSearch"
  13. @select="onSearch"
  14. />
  15. </template>
  16. <script>
  17. import { keywordSuggest } from '@/api/search'
  18. export default {
  19. name: 'SearchBox',
  20. props: {
  21. sw: {
  22. type: String,
  23. default: 'width:60%'
  24. }
  25. },
  26. data() {
  27. return {
  28. restaurants: [],
  29. placeholder: '想要搜点神马呢',
  30. keyword: '',
  31. timer: null
  32. }
  33. },
  34. created() {
  35. },
  36. methods: {
  37. // 重点:当框中的改变时触发该方法,elementui自动设置了防抖,参见debounce属性
  38. // queryString 为输入框中的值。cb为返回显示列表的回调函数
  39. querySearchAsync(queryString, cb) {
  40. if (queryString === '') {
  41. return
  42. }
  43. setTimeout(() => {
  44. keywordSuggest(queryString).then(res => {
  45. if (res.code === 0) {
  46. this.restaurants = res.data.map((item) => {
  47. return {
  48. value: item.keyword,
  49. rank: 1
  50. }
  51. })
  52. // 如果 cb 返回一个空数组, 那么模糊搜索输入建议的下拉选项会因为 length 为 0 而消失
  53. // cb([])
  54. cb(this.restaurants)
  55. } else {
  56. }
  57. })
  58. }, 500);
  59. },
  60. // select 事件或 enter 键事件
  61. onSearch() {
  62. console.log('回车事件')
  63. // 正则去空格
  64. if (this.keyword.replace(/\s*/g, '')) {
  65. this.toSearchPage()
  66. } else {
  67. this.$message({
  68. showClose: true,
  69. message: '不能为空!',
  70. type: 'warning'
  71. })
  72. }
  73. },
  74. // 跳转搜索页面,传递搜索框的参数
  75. toSearchPage() {
  76. const currentPath = this.$route.path
  77. if (currentPath === '/search') {
  78. this.$router.push({
  79. path: '/search',
  80. query: {
  81. keyword: this.keyword,
  82. pageNumber: 1
  83. }
  84. })
  85. this.$router.go(0)
  86. } else {
  87. const routeUrl = this.$router.resolve({
  88. path: '/search',
  89. query: {
  90. keyword: this.keyword,
  91. pageNumber: 1
  92. }
  93. })
  94. window.open(routeUrl.href, '_blank')
  95. }
  96. }
  97. }
  98. }
  99. </script>
  100. <style scoped>
  101. </style>