| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <template>
- <!--搜索框-->
- <el-autocomplete
- v-model="keyword"
- :fetch-suggestions="querySearchAsync"
- :placeholder="placeholder"
- clearable
- suffix-icon="el-icon-search"
- size="medium"
- :debounce="1000"
- :style="sw"
- @keyup.enter.native="onSearch"
- @select="onSearch"
- />
- </template>
- <script>
- import { keywordSuggest } from '@/api/search'
- export default {
- name: 'SearchBox',
- props: {
- sw: {
- type: String,
- default: 'width:60%'
- }
- },
- data() {
- return {
- restaurants: [],
- placeholder: '想要搜点神马呢',
- keyword: '',
- timer: null
- }
- },
- created() {
- },
- methods: {
- // 重点:当框中的改变时触发该方法,elementui自动设置了防抖,参见debounce属性
- // queryString 为输入框中的值。cb为返回显示列表的回调函数
- querySearchAsync(queryString, cb) {
- if (queryString === '') {
- return
- }
- setTimeout(() => {
- keywordSuggest(queryString).then(res => {
- if (res.code === 0) {
- this.restaurants = res.data.map((item) => {
- return {
- value: item.keyword,
- rank: 1
- }
- })
- // 如果 cb 返回一个空数组, 那么模糊搜索输入建议的下拉选项会因为 length 为 0 而消失
- // cb([])
- cb(this.restaurants)
- } else {
- }
- })
- }, 500);
- },
- // select 事件或 enter 键事件
- onSearch() {
- console.log('回车事件')
- // 正则去空格
- if (this.keyword.replace(/\s*/g, '')) {
- this.toSearchPage()
- } else {
- this.$message({
- showClose: true,
- message: '不能为空!',
- type: 'warning'
- })
- }
- },
- // 跳转搜索页面,传递搜索框的参数
- toSearchPage() {
- const currentPath = this.$route.path
- if (currentPath === '/search') {
- this.$router.push({
- path: '/search',
- query: {
- keyword: this.keyword,
- pageNumber: 1
- }
- })
- this.$router.go(0)
- } else {
- const routeUrl = this.$router.resolve({
- path: '/search',
- query: {
- keyword: this.keyword,
- pageNumber: 1
- }
- })
- window.open(routeUrl.href, '_blank')
- }
- }
- }
- }
- </script>
- <style scoped>
- </style>
|