AI原生前端开发(037):AI辅助的Vue 3开发最佳实践

前言

Vue 3的Composition API非常强大!AI可以帮我们更好地使用Vue 3开发!


1. Vue 3 Composition API AI辅助开发

1.1 组合式函数(Composables)

javascript 复制代码
/* 提示词:
"写一个Vue 3的useCounter composable"
*/

// composables/useCounter.ts
import { ref, computed } from 'vue';

/**
 * 计数器组合式函数
 * 
 * @example
 * ```vue
 * <script setup>
 * const { count, increment, decrement, double } = useCounter(0);
 * </script>
 * ```
 */
export function useCounter(initialValue = 0) {
  const count = ref(initialValue);

  const increment = () => {
    count.value++;
  };

  const decrement = () => {
    count.value--;
  };

  const double = computed(() => count.value * 2);

  const reset = () => {
    count.value = initialValue;
  };

  return {
    count,
    increment,
    decrement,
    double,
    reset
  };
}

// 使用示例
/*
<template>
  <div class="p-4">
    <p>计数: {{ count }}</p>
    <p>双倍: {{ double }}</p>
    <button @click="increment" class="px-4 py-2 bg-blue-600 text-white rounded mr-2">
      +1
    </button>
    <button @click="decrement" class="px-4 py-2 bg-gray-600 text-white rounded mr-2">
      -1
    </button>
    <button @click="reset" class="px-4 py-2 bg-red-600 text-white rounded">
      重置
    </button>
  </div>
</template>

<script setup lang="ts">
import { useCounter } from './composables/useCounter';

const { count, increment, decrement, double, reset } = useCounter(10);
</script>
*/

1.2 响应式数据获取

javascript 复制代码
/* 提示词:
"写一个Vue 3的useFetch composable用于数据获取"
*/

// composables/useFetch.ts
import { ref, isRef, unref, watchEffect } from 'vue';

/**
 * 数据获取组合式函数
 */
export function useFetch<T>(url: string | (() => string)) {
  const data = ref<T | null>(null);
  const loading = ref(true);
  const error = ref<Error | null>(null);

  const doFetch = async (fetchUrl: string) => {
    loading.value = true;
    error.value = null;
    try {
      const response = await fetch(fetchUrl);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      data.value = await response.json();
    } catch (err) {
      error.value = err instanceof Error ? err : new Error('Unknown error');
    } finally {
      loading.value = false;
    }
  };

  if (isRef(url)) {
    watchEffect(() => doFetch(url.value));
  } else if (typeof url === 'function') {
    watchEffect(() => doFetch(url()));
  } else {
    doFetch(url);
  }

  return { data, loading, error, refetch: () => doFetch(unref(url)) };
}

2. Vue 3 SFC开发规范

vue 复制代码
<!-- AI生成的标准Vue 3 SFC模板 -->
<template>
  <div class="my-component">
    <h2 class="title">{{ title }}</h2>
    <slot />
    <button @click="handleClick" :disabled="disabled">
      {{ buttonText }}
    </button>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';

interface Props {
  /** 标题 */
  title: string;
  /** 是否禁用 */
  disabled?: boolean;
}

interface Emits {
  (e: 'click', value: number): void;
}

const props = withDefaults(defineProps<Props>(), {
  disabled: false
});

const emit = defineEmits<Emits>();

const count = ref(0);

const buttonText = computed(() => `点击了 ${count.value} 次`);

const handleClick = () => {
  if (!props.disabled) {
    count.value++;
    emit('click', count.value);
  }
};
</script>

<style scoped>
.my-component {
  padding: 1rem;
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
}

.title {
  font-weight: 700;
  font-size: 1.25rem;
  margin-bottom: 1rem;
}

button {
  padding: 0.5rem 1rem;
  background-color: #2563eb;
  color: white;
  border-radius: 0.25rem;
}

button:disabled {
  opacity: 0.5;
}
</style>

3. 今日小结

这一篇我们学习了:

  1. Vue 3 Composables开发
  2. Vue 3 SFC规范

4. 下篇预告

下一篇,我们学习 AI辅助的Next.js 15全栈开发!

相关推荐
翼帆44 分钟前
我用 AI 复刻了 CodeTank,重温代码坦克
前端·javascript·开源·ai编程·游戏开发·codetank
有趣的老凌1 小时前
学习MarkDown笔记
前端
掘金者阿豪1 小时前
数据库选型到底应该看什么?从业务需求到技术架构的实践分析
前端·后端
徐小夕2 小时前
万字拆解:零向量库、无模型微调,SAG2 凭什么刷新多跳问答 SOTA
前端·vue.js·github
黑土豆2 小时前
用 drawink 给业务页面加一层画板:从网页批注到无限板书
前端·javascript·github
恋猫de小郭3 小时前
Flutter 3.50.0 Release 的第一个崩溃,修好了,还没 hotfix
android·前端·flutter
IT_陈寒17 小时前
Redis那个过期删除策略,差点让我线上崩了
前端·人工智能·后端
jianqiang.xue17 小时前
Espressif-IDE进入维护模式:乐鑫把ESP32开发的宝押给VS Code
前端·css·ide
特创数字科技17 小时前
纯本地离线运行的文档脱敏工具(技术分享)
前端·驱动开发·python
心之语歌18 小时前
uni-app uts原生插件开发:uts 与 Kotlin 交互踩坑实录(附解决方案)
前端·后端