一位客户要求我研究 Symfony UX 的Live Components以在内部项目中使用。我们/他们已经脱离了它的 alpha 状态,而且它可能会随着时间的推移而改变和打破,所以没有必要指出这一点。
问题是:我一切正常,但 Live 组件就像常规的 Twig 组件一样,在不刷新页面的情况下实际上不会交互式更新。我已经从字面上从文档中获取了一个示例,试图让它运行,但它只是不会更新。有熟悉这些组件的人能够指出我可能做错了什么吗?
首先,我已将该组件包含在 Composer 中:
"require": {
...
"symfony/ux-live-component": "^2.4",
...
}
Run Code Online (Sandbox Code Playgroud)
package.json还包含所需的内容:
"devDependencies": {
...
"@hotwired/stimulus": "^3.0.0",
"@symfony/stimulus-bridge": "^3.2.0",
"@symfony/ux-live-component": "file:vendor/symfony/ux-live-component/assets",
...
}
Run Code Online (Sandbox Code Playgroud)
我的 webpack 配置中启用了 Stimulus 桥:
Encore.enableStimulusBridge('./assets/controllers.json')
Run Code Online (Sandbox Code Playgroud)
我已将其引导文件包含在我的主 JS 文件中:
import './bootstrap';
Run Code Online (Sandbox Code Playgroud)
最后我制作了这个组件和模板:
<?php
declare(strict_types=1);
namespace App\Component;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;
#[AsLiveComponent('random_number')]
class RandomNumberComponent
{
use DefaultActionTrait;
#[LiveProp(writable: true)]
public int $max = 1000;
public function getRandomNumber(): int
{
return rand(0, $this->max);
}
}
Run Code Online (Sandbox Code Playgroud)
<div {{ attributes }}>
<p>Random number: <strong>{{ this.randomNumber }}</strong></p>
<p>Generating a number between 0 and {{ max }}</p>
<div class="form-group mb-3">
<label>Max</label>
<input class="form-control" type="number" data-model="max">
</div>
<button data-action="live#$render" class="btn btn-primary">Generate a new number!</button>
</div>
Run Code Online (Sandbox Code Playgroud)
单击按钮或更改输入的值没有任何效果。当我刷新页面时,我确实得到了一个不同的随机数,因此组件本身正在工作,只是异步部分没有工作。
我的 javascript 控制台相当无用,没有错误或警告,只有 Stimulus 本身的一些日志记录,这似乎表明至少 Stimulus 本身正在按预期工作:
application #starting <stimulus.js:1683>
application #start <stimulus.js:1683>
Run Code Online (Sandbox Code Playgroud)
这里有没有人足够熟悉这项新技术来为我指明正确的方向?
今天有这个确切的问题。从您的日志来看,刺激控制器似乎没有被加载。
确保您的controllers.json文件包含控制器:
{
"controllers": {
"@symfony/ux-live-component": {
"typed": {
"enabled": true,
"fetch": "eager",
"autoimport": {
"@symfony/ux-live-component/styles/live.css": true
}
}
}
},
"entrypoints": []
}
Run Code Online (Sandbox Code Playgroud)
您还bootstrap.js应该包含以下内容:
import { startStimulusApp } from '@symfony/stimulus-bridge';
// Registers Stimulus controllers from controllers.json and in the controllers/ directory
export const app = startStimulusApp(require.context(
'@symfony/stimulus-bridge/lazy-controller-loader!./controllers',
true,
/\.(j|t)sx?$/
));
Run Code Online (Sandbox Code Playgroud)