x-text 文本绑定 #

什么是 x-text? #

x-text 指令用于设置元素的文本内容。它会替换元素内部的所有文本,并自动转义 HTML 标签。

基本语法 #

html
<span x-text="表达式"></span>

基本用法 #

绑定简单值 #

html
<div x-data="{ message: 'Hello Alpine!' }">
    <p x-text="message"></p>
</div>

绑定表达式 #

html
<div x-data="{ firstName: 'John', lastName: 'Doe' }">
    <p x-text="firstName + ' ' + lastName"></p>
</div>

绑定计算属性 #

html
<div x-data="{
    items: ['Apple', 'Banana', 'Orange'],
    get itemCount() {
        return this.items.length
    }
}">
    <p>共有 <span x-text="itemCount"></span> 个项目</p>
</div>

绑定函数结果 #

html
<div x-data="{
    price: 100,
    formatPrice(value) {
        return '¥' + value.toFixed(2)
    }
}">
    <p x-text="formatPrice(price)"></p>
</div>

x-text vs 插值表达式 #

Alpine.js 不支持 Vue 风格的插值表达式 {{ }},必须使用 x-text

html
<div x-data="{ name: 'John' }">
    <p x-text="name"></p>
</div>

x-text vs x-html #

特性 x-text x-html
HTML 解析 不解析,原样输出 解析 HTML
XSS 安全 安全 有风险
使用场景 纯文本内容 富文本内容

x-text 示例 #

html
<div x-data="{ content: '<strong>Bold</strong>' }">
    <p x-text="content"></p>
</div>

输出:<strong>Bold</strong>(文本,不会加粗)

x-html 示例 #

html
<div x-data="{ content: '<strong>Bold</strong>' }">
    <p x-html="content"></p>
</div>

输出:Bold(HTML 被解析)

实用示例 #

用户信息展示 #

html
<div x-data="{
    user: {
        name: 'John Doe',
        email: 'john@example.com',
        role: 'Admin'
    }
}">
    <h2 x-text="user.name"></h2>
    <p x-text="user.email"></p>
    <span x-text="'角色: ' + user.role"></span>
</div>

计数器 #

html
<div x-data="{ count: 0 }">
    <button @click="count--">-</button>
    <span x-text="count"></span>
    <button @click="count++">+</button>
</div>

状态显示 #

html
<div x-data="{
    status: 'loading',
    statusText() {
        const texts = {
            loading: '加载中...',
            success: '加载成功',
            error: '加载失败'
        }
        return texts[this.status]
    }
}">
    <p x-text="statusText()"></p>
    <button @click="status = 'success'">成功</button>
    <button @click="status = 'error'">失败</button>
</div>

列表统计 #

html
<div x-data="{
    todos: [
        { done: true },
        { done: false },
        { done: true }
    ],
    get completed() {
        return this.todos.filter(t => t.done).length
    },
    get total() {
        return this.todos.length
    }
}">
    <p x-text="`已完成 ${completed}/${total} 项`"></p>
</div>

格式化显示 #

html
<div x-data="{
    date: new Date(),
    formatDate(date) {
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        })
    }
}">
    <p x-text="formatDate(date)"></p>
</div>

动态标题 #

html
<div x-data="{
    currentPage: 'home',
    getTitle() {
        const titles = {
            home: '首页',
            about: '关于我们',
            contact: '联系我们'
        }
        return titles[this.currentPage]
    }
}">
    <h1 x-text="getTitle()"></h1>
    <button @click="currentPage = 'home'">首页</button>
    <button @click="currentPage = 'about'">关于</button>
    <button @click="currentPage = 'contact'">联系</button>
</div>

注意事项 #

1. 替换所有内容 #

x-text 会替换元素的所有文本内容:

html
<div x-data="{ name: 'John' }">
    <p x-text="name">原有内容会被替换</p>
</div>

2. 空值处理 #

html
<div x-data="{ value: null }">
    <span x-text="value"></span>
</div>

输出空字符串,不会显示 “null”。

3. 数字转换 #

html
<div x-data="{ count: 0 }">
    <span x-text="count"></span>
</div>

数字会自动转换为字符串。

4. 布尔值 #

html
<div x-data="{ active: true }">
    <span x-text="active"></span>
</div>

输出 “true”。

小结 #

x-text 指令要点:

  • 设置元素的文本内容
  • 自动转义 HTML 标签
  • 支持表达式和函数调用
  • 替换元素的所有文本内容
  • 安全,防止 XSS 攻击

下一章,我们将学习 x-html 指令进行 HTML 内容绑定。

最后更新:2026-03-28