SearchBar.vue 1.71 KB
<template>
  <FrostedGlass class="px-4 py-2 mx-4 my-3 flex items-center">
    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
    </svg>
    <input
      type="text"
      :placeholder="placeholder"
      v-model="localValue"
      class="bg-transparent outline-none flex-1 text-gray-700 placeholder-gray-400"
      @input="handleSearch"
      @blur="handleBlur"
    />
  </FrostedGlass>
</template>

<script setup>
import { watch, ref } from 'vue'
import { useRouter } from 'vue-router'
import FrostedGlass from './FrostedGlass.vue'

const router = useRouter()

const props = defineProps({
  placeholder: {
    type: String,
    default: '搜索'
  },
  modelValue: {
    type: String,
    default: ''
  },
  isCoursePage: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['search', 'blur', 'update:modelValue'])

const localValue = ref(props.modelValue)

watch(() => props.modelValue, (newValue) => {
  localValue.value = newValue
})

const handleSearch = () => {
  emit('update:modelValue', localValue.value)
  emit('search', localValue.value)
}

const handleBlur = () => {
  const query = localValue.value
  emit('blur', query)
  // 根据页面类型决定路由行为
  if (props.isCoursePage) {
    // 在课程页面,跳转到课程列表页
    router.push({
      path: '/courses-list',
      query: { keyword: localValue.value }
    })
  } else {
    // 在课程列表页,只更新URL参数
    router.replace({ query: { ...router.currentRoute.value.query, keyword: localValue.value } })
  }
}
</script>