开发者问题收集

如何在 javascript 中使用 Livewire 组件?

2021-09-11
7029

查看文档 https://laravel-livewire.com/docs/2.x/events#from-js 在 javascript 中使用 Livewire 组件

<script>
    Livewire.emit('postAdded')
</script>

我不明白 Livewire 是什么?声明的 var?我如何获取它。 我需要从 JS 代码中获取某些 var 的值并运行组件方法。 我该怎么做?

修改后的块 # 2:

在我的组件模板中定义:

<div class="admin_page_container" id="facilities_admin_page_container">
   ...

在我的 alpinejs 组件的方法中我这样做

function adminFacilitiesComponent() {
    return {
        getSubmitLabel: function (component) {
            const doc = document.getElementById("facilities_admin_page_container");
            console.log('doc::')
            console.log(doc)

            var updateMode = window.livewire.find(doc.getAttribute("wire:updateMode"))
            // But I got error : index.js:31 Uncaught (in promise) TypeError: Cannot read property '$wire' of undefined
            // I see content of doc in browser's console : https://prnt.sc/1sdu4f1
            console.log('updateMode::')
            console.log(updateMode)

在我的组件中我已经定义:

namespace App\Http\Livewire\Admin;

...
class Facilities extends Component
{
    ...
    public $updateMode = 'browse';

我只是尝试在 JS getSubmitLabel 函数中获取 $updateMode 的值...

谢谢!

2个回答

回答您的问题:livewire 全局对象来自哪里:您在布局主体中注入了 livewire 脚本:

<html>
<head>
    ...
    @livewireStyles
</head>
<body>
    ...
    @livewireScripts
</body>
</html>

https://laravel-livewire.com/docs/2.x/installation

livewire 全局对象可通过 window.Livewire 获得。您正在寻找的方法可能是

Livewire.emitTo(componentName, eventName, ...params)

确保调用此方法时 livewire 对象确实可用。

有关所有可用方法,请参阅 https://laravel-livewire.com/docs/2.x/reference

要在 javascript 中获取组件,请尝试:

const doc = document.getElementById("myComponent");
window.livewire.find(doc.getAttribute("wire:id"))
DarkLeafyGreen
2021-09-14

Livewire recommends that you use AlpineJS for most of your JavaScript needs, but it does support using tags directly inside your component's view.

<!DOCTYPE html>
<html>
  <head>
     @livewireStyles
  </head>

<body>
      <p>This is My Component Call </p>
      @livewire('blog-component')

@livewireScripts
     <script>
     Livewire.emit('postAdded') //also write Javascript Hear
     
       document.addEventListener('livewire:load', function () {
        // Your JS here.
    })
     </script>

Reference
https://laravel-livewire.com/docs/2.x/inline-scripts https://laravel-livewire.com/docs/2.x/reference

Sarthak Raval
2021-09-14