Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

alpine.js - AlpineJS trigger native JS event with x-model (woocommerce cart)

Trying to use AlpineJS in Woocommerce checkout. I have input number field with + - indicators to increase value, simplefield code:

<div x-data="{ qty: 1 }">
  <i @click="qty = qty > 2 ? qty - 1 : 1" class="icon-left-open"></i>

  <input type="number" x-model="qty">

  <i @click="qty = qty + 1" class="icon-right-open"></i>
</div>

So the problem is that when the input value changes woocommerce "update cart" button still has a disabled state. I thought this was happing because x-model and 2-way binding don't fire native change/input events?

How to tell woocommerce that value changed?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can "watch" an x-data variable using $watch.

You can find out more about $watch here: https://github.com/alpinejs/alpine#watch

For example, this watches the "qty" value and if is changed it'll dispatch a "qty_true" event.

x-init="$watch('qty',value => { if (value) $dispatch('qty_true'); })"

Here's a version of your code with $watch, and the "qty_true" event listener.

<div x-data="{ qty: 1 }" x-init="$watch('qty',value => { if (value) $dispatch('qty_true'); })">
    <i @click="qty = qty > 2 ? qty - 1 : 1" class="icon-left-open"></i>
        
    <input type="number" x-model="qty">
        
    <i @click="qty = qty + 1" class="icon-right-open"></i>
</div>

<script type="text/javascript">
    window.addEventListener( 'qty_true', ( e ) => {
        console.log( 'qty now evaluates to true' );
        // enable your button here
    } );
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...