You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3:将搜索组件的Options API转换为Composition API(含v-model与watch)

Options API 转 Composition API 实操指引

核心转换对应关系

  • data → 使用 ref() 或 reactive() 声明响应式变量
  • watch → 使用 watch() 或 watchEffect() 函数
  • methods → 直接在 <script setup> 中定义普通函数

示例转换(基于典型搜索组件场景)

原 Options API 代码

<template>
  <input v-model="searchText" placeholder="输入搜索内容" />
  <button @click="handleSearch">搜索</button>
</template>

<script>
export default {
  props: {
    initialValue: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      searchText: '',
      debounceTimer: null
    }
  },
  mounted() {
    this.searchText = this.initialValue
  },
  watch: {
    searchText(newVal) {
      this.debounceSearch(newVal)
    }
  },
  methods: {
    debounceSearch(val) {
      if (this.debounceTimer) clearTimeout(this.debounceTimer)
      this.debounceTimer = setTimeout(() => {
        this.$emit('search', val)
      }, 300)
    },
    handleSearch() {
      this.$emit('search', this.searchText)
    }
  }
}
</script>

转换后的 <script setup> 代码

<template>
  <input v-model="searchText" placeholder="输入搜索内容" />
  <button @click="handleSearch">搜索</button>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'

// 已定义的props
const props = defineProps({
  initialValue: {
    type: String,
    default: ''
  }
})
// 声明emit
const emit = defineEmits(['search'])

// data转换:用ref声明响应式变量
const searchText = ref('')
const debounceTimer = ref(null)

// 复用已有的onMounted逻辑
onMounted(() => {
  searchText.value = props.initialValue
})

// watch转换:使用watch函数监听响应式变量
watch(searchText, (newVal) => {
  debounceSearch(newVal)
})

// methods转换:直接定义普通函数
function debounceSearch(val) {
  if (debounceTimer.value) clearTimeout(debounceTimer.value)
  debounceTimer.value = setTimeout(() => {
    emit('search', val)
  }, 300)
}

function handleSearch() {
  emit('search', searchText.value)
}
</script>

关键注意事项

  • 响应式变量在脚本中访问必须加 .value,模板中可直接使用
  • 若原data是复杂对象,用 reactive() 声明,解构时需配合 toRefs() 保持响应式
  • watch 监听多个源时,传入响应式变量数组即可
  • 组件通信统一用 defineProps 和 defineEmits,替代原选项式的props和$emit
  • 生命周期钩子直接从vue导入使用,无需挂载到选项上

内容的提问来源于stack exchange,提问作者weirdloop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 09:00:51