vue3 + ts <script setup>语法糖

这里是引用

1.data
2.computed
3.父传子
4.子传父
5.原型链绑定和组件使用
6.父子组件 v-model
7.nextTick
8.插槽
9.路由useRoute和useRouter
10.路由守卫
11.生命周期
12.父组件调子组件的方法 ref
13.store
14.watch

1.data

<template>
  <h1>{
   
   {
   
    name }}</h1>
  <h1>{
   
   {
   
    state.age }}</h1>
  <h1>{
   
   {
   
    sex }}</h1>
</template>

<script setup lang="ts">
import {
   
    reactive, ref, toRefs } from 'vue'
  // ref声明响应式数据,用于声明基本数据类型
  //const name = ref('东东吖')
    const name =ref<string>("")
  // 修改
  name.value = '小鲁班'

  // reactive声明响应式数据,用于声明引用数据类型
  const state = reactive({
   
   
    age: 24,
    sex: '男'
  })
  // 修改
  state.age = 24
  
  // 使用toRefs解构  template可直接使用{
   
   {name}}、{
   
   {sex}}
  const {
   
   age, sex} = toRefs(state)
  
</script>

2.computed

<template>
  <h1>{
   
   {
   
    count }}</h1>
  <h1>{
   
   {
   
   doubleCount}}</h1>
</template>

<script setup lang="ts">
import {
   
    ref,computed } from 'vue'
 // ref声明响应式数据,用于声明基本数据类型
  const count = ref(1)
  //computed获取双倍count' 
  const doubleCount =computed(()=>{
   
   
    return count.value*2
  })
</script>

3.父传子

父组件

<script setup lang="ts">
// 引入子组件(组件自动注册)
import HelloWorld from './components/HelloWorld.vue'
</script>

<template>
  <HelloWorld msg="东东吖" />
</template>

<style>

</style>

子组件

<template>
{
   
   {
   
   props.msg}}
<!-- 可省略props 
  <h1>{
   
   {
   
    msg }}</h1>
</template>

<script setup lang="ts">
// import { defineProps } from 'vue'
// defineProps在<script setup>中自动可用,无需导入
// 需在.eslintrc.js文件中【globals】下配置【defineProps: true】

// 声明props
const props = defineProps({
   
   
  msg: {
   
   
    type: String,
    default: "",
  },
});
</script>

4.子传父

//父组件:
<template>
  <HelloWorld :msg='state.msg' @changeMsg="changeMsg" />
</template>

<script setup lang="ts">
import {
   
    reactive } from "vue";
// 引入子组件(组件自动注册)
import HelloWorld from "./components/HelloWorld.vue";

const state = reactive({
   
   
  msg: "我是父组件原本的值",
});

const changeMsg = (val) => {
   
   
  state.msg = val;
};
</script>

子组件

//子组件:
<template>
  <h1>{
   
   {
   
    msg }}</h1>
<!-- 调用子传父事件 
  <button @click="changeMsg">点我</button>
</template>

<script setup lang="ts">
import {
   
    defineEmits } from "vue";
// import { defineEmits, defineProps } from 'vue'
// defineEmits和defineProps在<script setup>中自动可用,无需导入
// 需在.eslintrc.js文件中【globals】下配置【defineEmits: true】、【defineProps: true】

// 声明props
const props = defineProps({
   
   
  msg: {
   
   
    type: String,
    default: "",
  },
});

// 声明emit
const emit = defineEmits(["changeMsg"]);

// 声明子传父事件
const changeMsg = () => {
   
   
  emit("changeMsg", "我是子组件传过来的值");
};
</script>

5.原型链绑定和组件使用

main.ts

//main.ts

// 创建vue实例
const app=createApp(App)
// 获取原型
const prototype = app.config.globalProperties
// 绑定参数
prototype.name = '我是挂载在全局上的属性'
//第二种方式:
let helper = new TzPdmHelper(webSite);
app.config.globalProperties.$helper = helper;
//组件内获取使用
//引入
import {
   
    getCurrentInstance } from "vue";
// 获取原型
const {
   
    proxy } = getCurrentInstance();
// 输出
console.log(proxy.name);
console.log(proxy.$helper);

6.

在使用 **Vue 3 + TypeScript + `<script setup>`** 语法的 UniApp 项目中接入 DeepSeek 大模型 API,可以充分利用组合式 API 和类型系统来提升代码可维护性和开发体验。 以下是完整的实现方式、注意事项以及推荐的安全实践。 --- ### ✅ 功能目标 通过 `uni.request` 调用 DeepSeek 的对话接口(如 `deepseek-chat` 模型),实现用户输入问题后获取 AI 回复,并支持类型安全和结构化逻辑。 --- ### 🛠 完整示例代码(Vue 3 + TS + `<script setup>`) ```vue <template> <view class="container"> <textarea v-model="inputText" placeholder="请输入你的问题" class="input-area" /> <button @click="ask" :disabled="loading">{{ loading ? &#39;思考中...&#39; : &#39;发送&#39; }}</button> <view v-if="response" class="response-box"> <text>{{ response }}</text> </view> <view v-if="error" class="error-box"> <text>{{ error }}</text> </view> </view> </template> <script setup lang="ts"> import { ref } from &#39;vue&#39; // === 类型定义 === interface Message { role: &#39;user&#39; | &#39;assistant&#39; content: string } interface ChatResponse { id: string object: string created: number model: string choices: { index: number message: Message finish_reason: string }[] usage?: { prompt_tokens: number completion_tokens: number total_tokens: number } } // === 响应式数据 === const inputText = ref<string>(&#39;&#39;) const response = ref<string>(&#39;&#39;) const error = ref<string>(&#39;&#39;) const loading = ref<boolean>(false) // === 配置项(⚠️生产环境建议移至后端)=== const API_KEY = &#39;sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&#39; // 替换为你的 DeepSeek API Key const API_URL = &#39;https://api.deepseek.com/v1/chat/completions&#39; const MODEL_NAME = &#39;deepseek-chat&#39; // 或 deepseek-coder // === 方法:调用 DeepSeek API === const ask = async () => { if (!inputText.value.trim() || loading.value) return // 清空状态 response.value = &#39;&#39; error.value = &#39;&#39; loading.value = true try { const payload = { model: MODEL_NAME, messages: [{ role: &#39;user&#39;, content: inputText.value }] as Message[], temperature: 0.7, max_tokens: 1024, } const result = await uni.request<ChatResponse>({ url: API_URL, method: &#39;POST&#39;, header: { &#39;Authorization&#39;: `Bearer ${API_KEY}`, &#39;Content-Type&#39;: &#39;application/json&#39;, }, data: payload, }) const [err, res] = result if (err) { throw new Error(`网络错误: ${err.errMsg}`) } if (res.statusCode === 200 && res.data?.choices?.length > 0) { response.value = res.data.choices[0].message.content } else { error.value = `请求失败 (${res.statusCode}): ${res.data?.error?.message || &#39;未知错误&#39;}` } } catch (e: any) { console.error(&#39;DeepSeek 请求异常:&#39;, e) error.value = &#39;请求失败,请检查网络或 API Key 是否正确。&#39; } finally { loading.value = false } } </script> <style> .container { padding: 20px; display: flex; flex-direction: column; min-height: 100vh; } .input-area { width: 100%; height: 120px; border: 1px solid #ddd; border-radius: 8px; padding: 12px; font-size: 16px; margin-bottom: 15px; } button { background-color: #007aff; color: white; border: none; border-radius: 8px; padding: 12px 0; font-size: 16px; margin-bottom: 20px; } button:disabled { background-color: #aaa; } .response-box, .error-box { flex: 1; padding: 15px; background-color: #f9f9f9; border: 1px solid #eee; border-radius: 8px; white-space: pre-wrap; word-break: break-word; font-size: 15px; } .error-box { background-color: #fff0f0; color: #d00; border-color: #fcc; } </style> ``` --- ### 🔍 解释说明 | 特性 | 说明 | |------|------| | `<script setup lang="ts">` | 使用 Vue 3 组合式 API 并启用 TypeScript 支持 | | `ref<string>()` | 声明响应式变量并指定类型 | | `uni.request<T>()` 泛型 | 明确返回数据结构,提升类型安全性 | | 错误处理 | 区分网络错误 (`err`) 与 HTTP 状态码错误 | | 加载状态控制 | 使用 `loading` 防止重复提交 | | 样式适配 | 兼容 H5、小程序等多端 UI 表现 | --- ### ⚠️ 安全警告(非常重要) > ❗不要将 `API_KEY` 明文写在前端代码中!否则可能被反编译或抓包泄露,导致费用被盗用。 ✅ 推荐做法: ```bash 前端 (UniApp) → 自建后端服务 (/api/ai/chat) → DeepSeek API ``` 由你自己的服务器持有 API Key,并做限流、鉴权、日志监控。 你可以创建一个简单的 Node.js / Express / Koa / Flask 接口代理请求。 --- ### 💡 扩展建议 - 封装 `useDeepSeek()` 自定义 Hook(Composable) - 支持聊天历史记录(数组 `messages: Message[]`) - 添加流式响应(Streaming)支持(需后端配合 SSE/WebSocket) - 支持 `deepseek-coder` 模型进行编程问答 --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值