vue attribute中使用字符串模板 template string

博客提及在vue文件中,绑定属性可使用字符串模板,并给出了参考内容Combining string & variable in element attribute in Vue component template 。
Vue 3 的 TypeScript 项目中,`attribute` 是一个通用的前端术语,它本身并不是 Vue 或 TypeScript 特有的语法关键字。要理解“attribute”在 Vue 3 + TS 文件中的含义,需要结合上下文来看。 ### ✅ 什么是 attribute? **Attribute(属性)** 是 HTML 元素上的原始特性,用于配置元素或传递信息。例如: ```html <input type="text" value="hello" disabled> ``` - `type`、`value`、`disabled` 都是 **attributes**。 在 Vue 中,我们经常通过 attribute 向元素或组件传递数据。 --- ### 📌 在 Vue 3 + TypeScript 中常见的 attribute 使用场景 #### 1. **静态 attribute** 直接写在模板中: ```vue <template> <div id="app" class="container"> <MyComponent title="Welcome" count="1" /> </div> </template> ``` - `id`、`class`、`title`、`count` 都是 attributes。 - 对于原生 HTML 元素,这些会变成 DOM 属性。 - 对于组件,如果未在 `props` 中定义,则会被视为 **非 prop attribute**,默认会“透传”到根元素上(attribute inheritance)。 #### 2. **动态 attribute使用 v-bind)** ```vue <template> <MyComponent :title="dynamicTitle" :count="10" /> </template> <script setup lang="ts"> const dynamicTitle = 'Hello Vue 3'; </script> ``` #### 3. **在 TypeScript 中处理 attribute / props 类型** 当你编写一个组件并使用 `<script setup>` + TypeScript 时,你会用 `defineProps` 来声明接收哪些 **props**(即合法的输入属性),这些 props 实际上就是从父组件传递下来的 attributes。 ```vue <!-- MyComponent.vue --> <script setup lang="ts"> interface Props { title: string; count?: number; } // 声明接收的 props(也就是允许的 attributes) const props = defineProps<Props>(); </script> <template> <div>{{ title }} - {{ count }}</div> </template> ``` > 🔍 注意:这里的 `title` 和 `count` 是作为 **prop attributes** 被接收和使用的。 --- ### ⚠️ Attribute vs Property 的区别(重要) | 概念 | 说明 | |-----------|------| | **Attribute** | HTML 标签上的原始字符串值,属于 HTML 层面的概念。如 `<input value="123">` 中的 `value="123"` | | **Property** | DOM 元素对象上的 JavaScript 属性,是运行时的对象属性。比如 `el.value` 可能随用户输入改变 | Vue 主要操作的是 **property**,但你写的 `attribute` 会影响初始的 property。 --- ### 💡 特殊情况:Non-prop Attributes(非 prop 的 attribute) 如果你给组件传了一个 attribute,但它没有在 `props` 中声明,Vue 会将其自动添加到组件的根元素上。 ```vue <!-- 父组件 --> <MyComponent class="highlight" data-id="123" /> ``` ```vue <!-- 子组件 --> <template> <div>Title only</div> <!-- 假设这是根元素 --> </template> <script setup></script> ``` 结果渲染为: ```html <div class="highlight" data-id="123">Title only</div> ``` 你可以通过 `$attrs` 控制这种行为(在组合式 API 中用 `useAttrs()`): ```ts import { useAttrs } from 'vue' const attrs = useAttrs() console.log(attrs.class) // 'highlight' ``` --- ### ✅ 总结:Vue 3 + TS 中的 attribute 含义 | 场景 | attribute 的含义 | |------|------------------| | 模板中写在标签上的键值对 | 就是 HTML attribute,可能是 prop 也可能是普通 attribute | | 传给组件的 attribute | 如果匹配 `props` → 成为响应式 prop;否则成为 non-prop attribute 并透传 | | 在 TS 中 | 我们用接口定义 `Props` 类型来约束合法的 attribute 输入 | --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值