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全栈开发!

相关推荐
中科三方1 小时前
AI时代新攻击面:悬空DNS记录正在成为黑客的低成本入侵入口
服务器·前端·人工智能
努力变的更好1 小时前
H5与小程序之间的回调
前端·小程序·apache
汤米粥1 小时前
目前流行的前端 CSS 框架
前端·css·bootstrap·ant design·‌tailwind css·bulma
砚凝霜1 小时前
CTF Misc 签到 GXUST·CTF:查看源码 + HTML 注释 + Base64 解码(附 Base64 原理)
前端·html
徐小夕2 小时前
扒了JitWord的源码,我终于搞懂了企业级在线Word到底有多难写
前端·vue.js·github
lily5227832 小时前
工具池与分发
前端·chrome
徐小夕@趣谈前端2 小时前
老旧Word格式全支持!JitWord协同AI文档4.1,让Word文档无缝迁移到Web端
前端·人工智能·word
螺丝钉tina2 小时前
[Playwright][01] 从 Puppeteer 到 Playwright:为什么选择 Playwright + TypeScript?
前端·javascript·typescript
大团米线2 小时前
vite多环境合并打包config
javascript·vue.js·ecmascript