ComponentViewModel
By default, any Loki Component ships with an instance of Yireo\LokiComponents\Component\ComponentViewModel
which is instantiated in the PHTML template as a variable $viewModel
. However, it could be that you want to customize the methods in that ViewModel.
First, add the following to the XML file etc/loki_components.xml
:
<?xml version="1.0" encoding="UTF-8" ?>
<components xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Yireo_LokiComponents:etc/loki_components.xsd">
<component
name="loki-components.example"
viewModel="YireoTraining\ExampleLokiComponent\Component\Example\ExampleViewModel"
repository="YireoTraining\ExampleLokiComponent\Component\Example\ExampleRepository"
/>
</components>
Clean the configuration cache afterwards.
ComponentViewModel
classA new PHP class YireoTraining\ExampleLokiComponent\Component\Example\ExampleViewModel
now needs to be created in our module. This class is dubbed the ComponentViewModel
class in a component, because it extends upon a class Yireo\LokiComponents\Component\ComponentViewModel
.
namespace YireoTraining\ExampleLokiComponent\Component\Example;
use Yireo\LokiComponents\Component\ComponentViewModel;
class ExampleViewModel extends ComponentViewModel
{
}
There are no specific methods you need to declare to make this work.
Every time a Loki Component is being rendered, an x-data
argument is automatically added to its PHTML template output, referring to the AlpineJS component that should be used. By default, this is the AlpineJS component LokiComponent
. However, we can override this if we want to override the default behaviour.
In the previous document, we built an example where custom values value1
and value2
would need to be defined. First of all, we'll change the default AlpineJS component into a new component ExampleLokiComponent
(which has not been defined yet).
namespace YireoTraining\ExampleLokiComponent\Component\Example;
use Yireo\LokiComponents\Component\ComponentViewModel;
class ExampleViewModel extends ComponentViewModel
{
public function getJsComponentName(): ?string
{
return 'ExampleLokiComponent';
}
public function getJsData(): array
{
return [];
}
}
To add a new AlpineJS component ExampleLokiComponent
, let's add a block to the XML layout first:
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:View/Layout:etc/page_configuration.xsd">
<update handle="loki_components"/>
<body>
<referenceContainer name="loki-components">
<block
name="loki-components.script.component.example"
template="YireoTraining_ExampleLokiComponent::script/component/example-component.phtml"/>
</referenceContainer>
</body>
</page>
The PHTML template could look as follows:
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('ExampleLokiComponent', () => ({
...LokiComponentType,,
submit() {
this.post();
}
}));
});
</script>
Coming soon