magento2:在phtml里面用ko模板 并 传值给模板

本文介绍了如何在Magento2的PHTML文件中结合Knockout(KO)模板进行组件开发,详细讲解了如何创建自定义组件、编写JS逻辑以及定制模板,同时阐述了如何将数据从PHTML传递到KO模板,为实现更丰富的前端交互提供了指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

phtml:

<div class="custom-component" data-bind="scope:'custom_Component'">
    
    <!-- ko template: { name: $data.template, data: {current_product_id: "<?php echo $product_id; ?>",uidata: $data} } --><!-- /ko -->
    //uidata: $data 为component里的数据
</div>
<script type="text/x-magento-init">
{
    ".custom-component": {
        "Magento_Ui/js/core/app": {
            "components": {
                "custom_Component": {
                    "component": "Magento_Wishlist/js/components/custom-ajax"
                }
            }
        }
    }
}
</script>

//component:
custom-ajax.js:

define([
    'jquery',
    'uiComponent', 
    'ko'
],function ($, Component, ko) {
    'use strict';
    return Component.extend({
        defaults: {
            template: 'Magento_Wishlist/components/custom-wishlist'
        },
        variable1: ko.observable(false),
        variable2:'aaa2',
         variable3:'aaa3',
		current_page_url: document.location.href,
		
        initialize: function () {
            this._super();
            this._load();
            
        },
        _load: function () {
            var _this = this;
            .....
        },
		click_action: function(){
			 var _this = this.uidata, //调用uidata,此this指 template里传的data
               current_page_url =_this.current_page_url,
               _this_selector = $(event.currentTarget),
               product_id = _this_selector.data("product-id");  // 或者这个this.current_product_id
               ......
		}
      
      
    });

});

template:
custom-wishlist.html

<div class="custom-block" data-bind="click: uidata.click_action, attr: {'data-product-id': current_product_id}">
    <div class="block-wrapper">
            <span data-bind="css: uidata.variable1() ? uidata.variable2 : uidata.variable3"
            class="custom-action"></span>
    </div>
</div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值