英文:
use x-init and a setter to update x-data variable and reflect it in the frontend
问题
在初始化时调用函数以更改 x-data 变量并在前端反映它。在控制台中,该值为false,但在前端中,x-text 和 x-if 仍然会像它是true一样响应。如何使前端反映更改?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="//unpkg.com/alpinejs" defer></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div x-data="{ val: true }" x-init="setVal()">
<div><span x-text="val"></span></div>
<template x-if="val">
<div>Renders on x-if directive.</div>
</template>
</div>
<script>
function setVal() {
this.val = false;
console.log("val", this.val);
}
</script>
</body>
</html>
英文:
I am trying to call a function on init to change a x-data variable and reflect it in the frontend.
In the console the value is false but in the frontend the x-text and the x-if still react as if is true.
How do i get the frontend to reflect the change?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="//unpkg.com/alpinejs" defer></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div x-data="{ val: true }" x-init="setVal()">
<div><span x-text="val"></span></div>
<template x-if="val">
<div>Renders on x-if directive.</div>
</template>
</div>
<script>
function setVal() {
this.val = false;
console.log("val", this.val);
}
</script>
</body>
</html>
<!-- end snippet -->
答案1
得分: 1
你可以直接在x-init
指令内部改变状态,或者将setVal()
函数放在Alpine.js上下文中,以便它可以访问和修改数据。
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<div x-data="{ val: true }" x-init="val = false">
<div><span x-text="`val的值: ${val}`"></span></div>
</div>
<div x-data="{ val: true, setVal() { this.val = false } }" x-init="setVal()">
<div><span x-text="`val的值: ${val}`"></span></div>
</div>
<!-- end snippet -->
英文:
You can mutate a state directly inside x-init
directive, or put setVal()
function inside the Alpine.js context, so it can access and mutate the data.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<div x-data="{ val: true }" x-init="val = false">
<div><span x-text="`Value of val: ${val}`"></span></div>
</div>
<div x-data="{ val: true, setVal() {this.val = false} }" x-init="setVal()">
<div><span x-text="`Value of val: ${val}`"></span></div>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论