vue的script的三种写法

文章展示了Vue2和Vue3中实现搜索框组件的不同方法,包括使用ref和CompositionAPI来管理响应式数据,以及处理搜索和清除关键字的逻辑。Vue3的CompositionAPI和scriptsetup语法提供了更简洁和模块化的代码组织方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以搜索框为例子

vue2的写法
第一种

<template>
  <div>
    <el-input
      v-model="searchKeyword"
      placeholder="请输入搜索关键字"
      clearable
      @clear="clearSearch"
      @keydown.enter="handleSearch"
    />
    <el-button type="primary" @click="handleSearch">搜索</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: ''
    };
  },
  methods: {
    handleSearch() {
      // 执行搜索操作
      console.log('执行搜索操作,关键字:', this.searchKeyword);
      // 进行相关的搜索逻辑处理
    },
    clearSearch() {
      // 清空搜索关键字
      this.searchKeyword = '';
    }
  }
};
</script>

vue3的写法
第一种,我们使用了Vue 3的ref函数来创建响应式数据searchKeyword。在setup函数中定义了handleSearch方法和clearSearch方法,并将它们作为返回值暴露给模板使用。

使用Composition API的好处是可以将相关的逻辑进行组合,而不是按照选项的方式进行划分。这样,我们可以更方便地重用和组合逻辑代码,使代码更具可读性和可维护性。

请注意,使用Composition API时,我们不再使用data选项和传统的Options API写法,而是在setup函数中定义响应式数据和方法,并通过返回值暴露给模板使用

<template>
  <div>
    <el-input
      v-model="searchKeyword"
      placeholder="请输入搜索关键字"
      clearable
      @clear="clearSearch"
      @keydown.enter="handleSearch"
    />
    <el-button type="primary" @click="handleSearch">搜索</el-button>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const searchKeyword = ref('');

    const handleSearch = () => {
      // 执行搜索操作
      console.log('执行搜索操作,关键字:', searchKeyword.value);
      // 进行相关的搜索逻辑处理
    };

    const clearSearch = () => {
      // 清空搜索关键字
      searchKeyword.value = '';
    };

    return {
      searchKeyword,
      handleSearch,
      clearSearch
    };
  }
};
</script>

第三种

使用 script setup 语法,我们可以直接在脚本块中定义变量和方法,无需再通过return将它们导出。这种写法更加简洁和直观

<template>
  <div>
    <el-input
      v-model="searchKeyword"
      placeholder="请输入搜索关键字"
      clearable
      @clear="clearSearch"
      @keydown.enter="handleSearch"
    />
    <el-button type="primary" @click="handleSearch">搜索</el-button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const searchKeyword = ref('');

const handleSearch = () => {
  // 执行搜索操作
  console.log('执行搜索操作,关键字:', searchKeyword.value);
  // 进行相关的搜索逻辑处理
};

const clearSearch = () => {
  // 清空搜索关键字
  searchKeyword.value = '';
};
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lionliu0519

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值