How to Use Javascript Mixins in Magento 2

Sometimes you want to extend some function or want to modify some data without overwriting javascript. In this article, I am going to explain to you how to use js mixins in Magento 2. Before we go with technical let me explain to you what is mixins and then we'll see how to use mixins in Magento 2.

What is Mixins?

According to adobe commerce guide Mixin is a class whose methods are added to, or mixed in, with another class.

A base class includes the methods from a mixin instead of inheriting from it. This allows you to add to or augment the behavior of the base class by adding different mixins to it.

How to use Javascript mixins in Magento 2?

To use mixins in Magento 2 please follow the below steps.

Step 1: Create requirejs-config.js at app/code/Vendor/CustomModule/view/frontend and paste the below code. You need to change code as per your requirement.

saveCopyzoom_out_map
var config = { config: { mixins: { 'Magento_Checkout/js/action/set-shipping-information': { 'Vendor_CustomModule/js/action/set-shipping-information-mixin': true } } } };

In above code I've extended Magento_Checkout/js/action/set-shipping-information js file with my Vendor_CustomModule/js/action/set-shipping-information-mixin js. You'll extend any other js files according to your requirement.

Step 2: Create set-shipping-information-mixin.js file at app/code/Vendor/CustomModule/view/frontend/web/js/action to extend original function.

Here I just try to append some data to shipping address just for an example. You can write here your code according to your requirement.

saveCopyzoom_out_map
define([ 'jquery', 'mage/utils/wrapper', 'Magento_Checkout/js/model/quote' ], function ($, wrapper, quote) { 'use strict'; return function (setShippingInformationAction) { return wrapper.wrap(setShippingInformationAction, function (originalAction) { var shippingAddress = quote.shippingAddress(); if (shippingAddress['customAttributes'] === undefined) { shippingAddress['customAttributes']= {} } shippingAddress['customAttributes']['custom_data'] = "Custom Value"; //console.log(quote.shippingAddress()); return originalAction(); }); }; });

Now, open Command line in folder root of magento and run the below commands.

saveCopyzoom_out_map
php bin/magento s:up php bin/magento s:s:d -f php bin/magento c:c

If you check console log quote.shippingAddress() in js then you will see custom_data is appened under the customAttributes with Custom Value.

That’s it,

We hope this Magento post helped you to know How to Use Javascript Mixins in Magento 2. Bookmark it for your future reference. Do comment below if you have any other questions or doubts.

P.S. Do share this post with your team.

Review other articles maybe it'll help you too.




Recent Articles
Tags
Newsletter
Chrome Extension
Copyright © 2024 devhooks.in All rights reserved.
Ads OFF toggle_off
wifi_off