Owl 2.8.1 核心语法速查表(新手专用)
这份速查表整合了官方文档核心知识点 + 实战验证过的正确写法,新手可直接对照使用,避免踩坑:
一、基础结构(必背)
| 功能 | 代码示例 |
|---|---|
| 1. 导入核心模块 | import { Component, mount, xml, useState } from "@odoo/owl"; |
| 2. 定义组件类 | class App extends Component { ... } |
| 3. 模板定义 | static template = xml 模板内容 ; |
| 4. 挂载组件 | mount(组件类, DOM节点) → mount(App, document.getElementById("app")); |
二、状态管理(useState)
| 功能 | 代码示例 |
|---|---|
| 1. 初始化状态 | setup() { this.state = useState({ count: 0 }); } |
| 2. 更新状态 | increment() { this.state.count++; } |
| 3. 复杂状态(对象) | this.state = useState({ user: { name: "Owl", age: 2 } }); |
| 4. 响应式更新 | 直接修改状态即可(Owl 自动更新视图)→ this.state.user.age = 3; |
三、模板语法(高频)
| 指令 | 作用 | 代码示例 |
|---|---|---|
t-esc |
输出变量/表达式 | <p>Counter: <t t-esc="state.count"/></p> |
t-on:事件名 |
绑定事件 | <button t-on-click="increment">增加</button> |
t-if |
条件渲染 | <p t-if="state.count > 5" style="color: red;">超过5啦!</p> |
t-else |
条件分支 | <p t-else>还没到5哦~</p> |
t-for |
循环渲染 | <div t-for="item in state.list" t-esc="item"/> |
t-bind:属性 |
绑定DOM属性 | <input t-bind:value="state.inputVal"/> |
四、组件生命周期(常用)
| 生命周期方法 | 执行时机 | 代码示例 |
|---|---|---|
setup |
组件初始化(最先执行) | 放 useState、方法定义等 |
mounted |
组件挂载到DOM后执行 | mounted() { console.log("组件挂载完成"); } |
willUnmount |
组件卸载前执行 | willUnmount() { console.log("组件即将卸载"); } |
五、新手避坑指南(关键)
| 坑点 | 错误示例 | 正确写法 |
|---|---|---|
| 1. 多余模板符号 | <p>Counter: <<t t-esc="state.count"/></p> |
<p>Counter: <t t-esc="state.count"/></p> |
| 2. 误用 createApp | import { createApp } from "@odoo/owl"; |
改用 mount 挂载(无 createApp 导出) |
| 3. 旧版 this.useState | this.state = this.useState({}); |
this.state = useState({});(单独导入) |
| 4. 挂载传实例 | mount(new App(), 节点) |
mount(App, 节点)(传类,不是实例) |
六、实战扩展示例(整合速查表)
(包含循环、条件、生命周期):
javascript
import { Component, mount, xml, useState } from "@odoo/owl";
class App extends Component {
static template = xml`
<div class="app">
<h1>hello, Owl! 🦉</h1>
<!-- 1. t-esc 输出 -->
<p>Counter: <t t-esc="state.count"/></p>
<!-- 2. t-if/t-else 条件 -->
<p t-if="state.count > 5" style="color: red;">超过5啦!</p>
<p t-else>还没到5哦~</p>
<!-- 3. t-for 循环 -->
<div>
循环示例:
<div t-for="num in state.numList" t-esc="num"/>
</div>
<!-- 4. 事件绑定 -->
<button t-on-click="increment">增加</button>
</div>
`;
setup() {
// 初始化状态(基础 + 数组)
this.state = useState({
count: 0,
numList: [1, 2, 3]
});
}
increment() {
this.state.count++;
// 循环数组响应式更新
if (this.state.count % 2 === 0) {
this.state.numList.push(this.state.count);
}
}
// 生命周期
mounted() {
console.log("组件挂载完成,初始count:", this.state.count);
}
}
// 挂载组件
mount(App, document.getElementById("app"));
速查表使用说明
- 开发时按「功能→代码示例」直接抄,无需翻文档;
- 遇到报错先查「避坑指南」,90%的新手问题都能解决;
- 扩展功能时参考「实战示例」,整合多个语法点。
后续使用【Props 传值】【组件嵌套】【Hooks 钩子】等内容时,请参考《Owl 2.8.1 进阶语法速查表(Props / 组件嵌套 / Hooks)》。