Magento2 中KnockoutJs 的应用

首先,我们需要创建registration.php和etc/module.xml文件:

Registration.php:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'Magenest_Feedback',
        __DIR__
    );
Module.xml:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magenest_Feedback"/>
</config>
Db_schema.xml:
<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
   <table name="magenest_feedback" resource="default" engine="innodb" comment="Magenest Feedback">
       <column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="true" comment="ID"/>
       <column xsi:type="int" name="product_id" nullable="false" comment="Product Id"/>
       <column xsi:type="int" name="order_id" comment="Order Id"/>
       <column xsi:type="int" name="customer_id" comment="Customer Id"/>
       <column xsi:type="varchar" name="message" length="255"  comment="Message"/>
       <column xsi:type="boolean" name="status" default="0"  comment="Status"/>
       <constraint xsi:type="primary" referenceId="PRIMARY">
           <column name="entity_id"/>
       </constraint>
       <index referenceId="magenest_feedback_entity_id" indexType="btree">
           <column name="entity_id"/>
       </index>
   </table>
</schema>

创建routes, controller, layout

routes: etc\frontend\routes.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
   <router id="standard">
       <route id="feedback" frontName="feedback">
           <module name="Magenest_Feedback"/>
       </route>
   </router>
</config>
controller:Controller\Customer\Index.php
<?php
/**
* Copyright © 2021 Magenest. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magenest\Feedback\Controller\Customer;


use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\View\Result\PageFactory;


class Index extends Action
{
   protected $_pageFactory;


   public function __construct(
    Context $context, 
    PageFactory $pageFactory
   ){
       parent::__construct($context);
       $this->_pageFactory = $pageFactory;
   }


   public function execute()
   {
       return $this->_pageFactory->create();
   }
}

到这里,您可以访问http://baseURL/feedback/customer/index默认Magento布局和空白内容区域

创建 layout view\frontend\layout\feedback_customer_index.xml:
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <body>
       <referenceContainer name="content">
           <block class="Magenest\Feedback\Block\Customer\Feedback" name="customer_feedback" template="Magenest_Feedback::customer_feedback.phtml"/>
       </referenceContainer>
   </body>
</page>

创建block, template

View\frontend\templates\customer_feedback.phtml
<?php
/**
* @var \Magenest\Feedback\Block\Customer\Feedback $block ;
*/
?>
<div id="feedback-form-data" data-bind="scope: 'feedback-data'">
   <!-- ko template: getTemplate() --> <!-- /ko -->
</div>


<script type="text/x-magento-init">
   {
       "*": {
           "Magento_Ui/js/core/app": {
               "components": {
                   "feedback-data": {
                       "component": "Magenest_Feedback/js/view/customer-feedback",
                       "feedbackData": <?php /* @escapeNotVerified */ echo $block->feedbackLastData(); ?>
                   }
               }
           }
       }
   }

</script>
Block\Customer\Feedback.php
<?php
/**
* Copyright © 2021 Magenest. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magenest\Feedback\Block\Customer;

use Magento\Framework\View\Element\Template;
use Magenest\Feedback\Model\ResourceModel\Feedback\CollectionFactory;
use Magento\Framework\Json\Helper\Data;

class Feedback extends Template
{
   protected $feedbackCollectionFactory;
   protected $jsonHelper;

   public function __construct(
       Template\Context $context,
       CollectionFactory $feedbackCollectionFactory,
       Data $jsonHelper,
       array $data = []
   ){
       $this->feedbackCollectionFactory = $feedbackCollectionFactory;
       $this->jsonHelper = $jsonHelper;
       parent::__construct($context, $data);
   }

   public function feedbackLastData(){
       //we get the last feedback
       $feedbackData = $this->feedbackCollectionFactory->create()
             ->getLastItem()->getData();
       return $this->jsonHelper->serialize($feedbackData);
   }
}

创建component ,template:

创建 component :view\frontend\web\js\customer_feedback.js:

define([
   'jquery',
   'ko',
   'uiComponent',
   'mage/url',
   'Magento_Ui/js/modal/alert',
], function($, ko, Component, url, alert) {
   return Component.extend({
       defaults: {
           template: 'Magenest_Feedback/customer-feedback',
           data : ko.observableArray([])
       },

       initialize: function () {
           this._super();
           this.data(this.feedbackData);
       },

       initObserver: function () {
           this._super();
       },

       sendFeedback: function ($param) {
           var data = {
               'order_id': $('#order_id').val(),
               'product_id': $('#product_id').val(),
               'message': $('#message').val(),
           };
           $.ajax({
               url: url.build('feedback/customer/save'),
               data: data,
               type: 'get',
               dataType: 'json',
               context: this,
               success: function (response) {
                   if (response.status === true){
                       this.data(response.newData);
                       alert({
                           content: $.mage.__('Thanks for Submitting.')
                       });
                   }
               },
           });
       }
   });
});
feedback view\frontend\web\template\customer-feedback.html:
<form class="form customer-feedback">
   <div class="field">
       <label class="label">
           <span><!-- ko i18n: 'Product Id'--><!-- /ko --></span>
       </label>
       <div class="control">
           <input id="product_id" name="product_id" type="number" value="" class="input-text">
       </div>
   </div>
   <div class="field">
       <label class="label">
           <span><!-- ko i18n: 'Order Id'--><!-- /ko --></span>
       </label>
       <div class="control">
           <input id="order_id" name="order_id" type="number" value="" class="input-text">
       </div>
   </div>
   <div class="field">
       <label class="label">
           <span><!-- ko i18n: 'Message'--><!-- /ko --></span>
       </label>
       <div class="control">
           <textarea id="message" name="message"></textarea>
       </div>
   </div>
   <br/>
   <div class="actions-toolbar">
       <div class="primary">
           <button type="submit" class="action primary" data-bind="click : sendFeedback">
               <span>Submit</span>
           </button>
       </div>
   </div>
</fieldset>
</form>
<table>
   <thead>
   <tr>
       <th><span data-bind="i18n: 'Id'"></span></th>
       <th><span data-bind="i18n: 'Product Id'"></span></th>
       <th><span data-bind="i18n: 'Order Id'"></span></th>
       <th><span data-bind="i18n: 'Message'"></span></th>
       <th><span data-bind="i18n: 'Status'"></span></th>
   </tr>
   </thead>
   <tbody data-bind="foreach: data">
       <tr>
           <td data-bind="text: entity_id"></td>
           <td data-bind="text: product_id"></td>
           <td data-bind="text: order_id"></td>
           <td data-bind="text: message"></td>
           <td data-bind="text: status"></td>
       </tr>
   </tbody>
</table>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容