The front-end framework Layui realizes the dynamic tree effect (the drop-down list on the left side of the book management system)

Table of contents

I. Introduction

1. What is a tree menu

2. Usage scenarios of the tree menu

2. Case realization

1. Demand analysis

2. Preparatory work

① Import dependencies

②Tools

BaseDao (general CRUD)

BuildTree (complete the conversion of flat data to parent-child level)

ResponseUtil (convert data into json format for echo)

③ Write entity

3.dao layer writing

4. servlet layer writing

5. jsp page construction

6. Case presentation


I. Introduction

Before completing the case, let's first understand what is a tree menu

1. What is a tree menu

        A tree menu is a user interface design pattern that is often used to organize and present a hierarchy of large amounts of information. It gets its name from the fact that the menu presents a structure similar to the branches and nodes of a tree. A tree menu usually consists of a main node and multiple child nodes, and each child node can have its own child nodes, forming a hierarchical structure of parent-child relationships .

        In a tree menu, a main node represents a top-level option or category, while child nodes represent specific options or subcategories associated with the main node. Users can browse more detailed levels by expanding or collapsing child nodes. Usually, the leaf node is the bottommost node, representing the most specific option or content.

        Tree menus are suitable for applications and websites that need to organize and present complex data or multi-level directories. They allow users to easily navigate and select desired options, providing a clean and intuitive way to browse and access information.

2. Usage scenarios of the tree menu

Tree menus are widely used in various applications and websites, the following are some common usage scenarios:

  • 1. File resource management : The tree menu can be used to browse and manage file resources, especially when files are organized into a multi-level directory structure. Users can expand and collapse directories to access desired files or folders.
  • 2. Organizational structure and personnel management : The organizational structure of an enterprise or organization can be visualized through a tree menu. Each node represents a department, team or individual, and users can view more detailed levels and information by expanding the node.
  • 3. Navigation menu : The main navigation menu of a website or application often uses a tree structure to display different pages or functional options. Users can expand or collapse menu items as needed to quickly locate the desired function or content.
  • 4. Product categories and catalog navigation : Online stores or e-commerce sites often use tree menus to organize product categories and categories. Users can browse and select products by expanding and collapsing different categories.
  • 5. Content management system : Tree menus are widely used in content management systems to organize and manage content such as pages, articles, categories, and tags of a website.

All in all, tree menus are suitable for any scenario where hierarchical data needs to be presented and organized to provide a clear and easy-to-navigate user interface.

2. Case realization

1. Demand analysis

We want to complete the list display on the left side of a book management system. The essential thing is the design of the table. The table design is related to the display of our jsp page. The following is my table design for your reference only.

It is also necessary to have data in the table design. Of course, don't write the table data casually, otherwise errors may occur! !

        The data here is very particular. The data we usually get through the dao layer is flat data, which does not meet our requirements. What we need is parent-child level data, so how to convert from flat data to What about our parent-child data? ? At this time, our table design plays a crucial role. We can see that the pids of the parent nodes are all 0, and the pids of their child nodes correspond to the ids of the parent nodes.

        It is concluded that we only need two methods, one is to query all the methods (to get the parallel data), and the other is to perform two for traversals on the same level data and add them to the new collection (parent-child container). The first for Add the data whose pid number is the top node, that is, the parent node, to the container. The second traversal compares the pid with the id in the new collection. If they are the same, it is the children in the new collection.

 

2. Preparatory work

Note: More details in the custom MVC trilogy I wrote.

① Import dependencies

Import our required dependencies into WebContent➡WEB-INF

Create a directory to store js/css and put the required files in

Package files shared by multiple pages into public files

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html ">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<!-- 引入layui.css-->
<link rel="stylesheet" href="${pageContext.request.contextPath}/static/js/layui/css/layui.css">

<!-- 引入layui.js-->
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/layui/layui.js"></script>


</head>

</html>

②Tools

Here we need to use tools

BaseDao (general CRUD)

package com.zking.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 所有Dao层的父类 BookDao UserDao OrderDao ...
 * 
 * @author Administrator
 *
 * @param <T>
 */
public class BaseDao<T> {

	/**
	 * 适合多表联查的数据返回
	 * @param sql
	 * @param pageBean
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public List<Map<String, Object>> executeQuery(String sql, PageBean pageBean)
			throws SQLException, InstantiationException, IllegalAccessException {

		List<Map<String, Object>> list = new ArrayList<>();
		Connection con = DBAccess.getConnection();
		PreparedStatement pst = null;
		ResultSet rs = null;

		/*
		 * 是否需要分页? 无需分页(项目中的下拉框,查询条件教员下拉框,无须分页) 必须分页(项目中列表类需求、订单列表、商品列表、学生列表...)
		 */
		if (pageBean != null && pageBean.isPagination()) {
			// 必须分页(列表需求)
			String countSQL = getCountSQL(sql);
			pst = con.prepareStatement(countSQL);
			rs = pst.executeQuery();
			if (rs.next()) {
				pageBean.setTotal(String.valueOf(rs.getObject(1)));
			}

			// 挪动到下面,是因为最后才处理返回的结果集
			// -- sql=SELECT * FROM t_mvc_book WHERE bname like '%圣墟%'
			// -- pageSql=sql limit (page-1)*rows,rows 对应某一页的数据
			// -- countSql=select count(1) from (sql) t 符合条件的总记录数
			String pageSQL = getPageSQL(sql, pageBean);// 符合条件的某一页数据
			pst = con.prepareStatement(pageSQL);
			rs = pst.executeQuery();
		} else {
			// 不分页(select需求)
			pst = con.prepareStatement(sql);// 符合条件的所有数据
			rs = pst.executeQuery();
		}

		// 获取源数据
		ResultSetMetaData md = rs.getMetaData();
		int count = md.getColumnCount();
		Map<String, Object> map = null;
		while (rs.next()) {
			map = new HashMap<>();
			for (int i = 1; i <= count; i++) {
//				map.put(md.getColumnName(i), rs.getObject(i));
				map.put(md.getColumnLabel(i), rs.getObject(i));
			}
			list.add(map);
		}
		return list;

	}

	/**
	 * 
	 * @param sql
	 * @param attrs
	 *            map中的key
	 * @param paMap
	 *            jsp向后台传递的参数集合
	 * @return
	 * @throws SQLException
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public int executeUpdate(String sql, String[] attrs, Map<String, String[]> paMap) throws SQLException,
			NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		Connection con = DBAccess.getConnection();
		PreparedStatement pst = con.prepareStatement(sql);
		for (int i = 0; i < attrs.length; i++) {
			pst.setObject(i + 1, JsonUtils.getParamVal(paMap, attrs[i]));
		}
		return pst.executeUpdate();
	}

	/**
	 * 批处理
	 * @param sqlLst
	 * @return
	 */
	public static int executeUpdateBatch(String[] sqlLst) {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			conn = DBAccess.getConnection();
			// 设置不自动提交
			conn.setAutoCommit(false);
			for (String sql : sqlLst) {
				stmt = conn.prepareStatement(sql);
				stmt.executeUpdate();
			}
			conn.commit();
		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
				throw new RuntimeException(e1);
			}
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			DBAccess.close(conn, stmt, null);
		}
		return sqlLst.length;
	}

	/**
	 * 通用的增删改方法
	 * 
	 * @param book
	 * @throws Exception
	 */
	public int executeUpdate(String sql, T t, String[] attrs) throws Exception {
		// String[] attrs = new String[] {"bid", "bname", "price"};
		Connection con = DBAccess.getConnection();
		PreparedStatement pst = con.prepareStatement(sql);
		// pst.setObject(1, book.getBid());
		// pst.setObject(2, book.getBname());
		// pst.setObject(3, book.getPrice());
		/*
		 * 思路: 1.从传进来的t中读取属性值 2.往预定义对象中设置了值
		 * 
		 * t->book f->bid
		 */
		for (int i = 0; i < attrs.length; i++) {
			Field f = t.getClass().getDeclaredField(attrs[i]);
			f.setAccessible(true);
			pst.setObject(i + 1, f.get(t));
		}
		return pst.executeUpdate();
	}

	/**
	 * 通用分页查询
	 * 
	 * @param sql
	 * @param clz
	 * @return
	 * @throws Exception
	 */
	public List<T> executeQuery(String sql, Class<T> clz, PageBean pageBean) throws Exception {
		List<T> list = new ArrayList<T>();
		Connection con = DBAccess.getConnection();
		;
		PreparedStatement pst = null;
		ResultSet rs = null;

		/*
		 * 是否需要分页? 无需分页(项目中的下拉框,查询条件教员下拉框,无须分页) 必须分页(项目中列表类需求、订单列表、商品列表、学生列表...)
		 */
		if (pageBean != null && pageBean.isPagination()) {
			// 必须分页(列表需求)
			String countSQL = getCountSQL(sql);
			pst = con.prepareStatement(countSQL);
			rs = pst.executeQuery();
			if (rs.next()) {
				pageBean.setTotal(String.valueOf(rs.getObject(1)));
			}

			// 挪动到下面,是因为最后才处理返回的结果集
			// -- sql=SELECT * FROM t_mvc_book WHERE bname like '%圣墟%'
			// -- pageSql=sql limit (page-1)*rows,rows 对应某一页的数据
			// -- countSql=select count(1) from (sql) t 符合条件的总记录数
			String pageSQL = getPageSQL(sql, pageBean);// 符合条件的某一页数据
			pst = con.prepareStatement(pageSQL);
			rs = pst.executeQuery();
		} else {
			// 不分页(select需求)
			pst = con.prepareStatement(sql);// 符合条件的所有数据
			rs = pst.executeQuery();
		}

		while (rs.next()) {
			T t = clz.newInstance();
			Field[] fields = clz.getDeclaredFields();
			for (Field f : fields) {
				f.setAccessible(true);
				f.set(t, rs.getObject(f.getName()));
			}
			list.add(t);
		}
		return list;
	}

	/**
	 * 将原生SQL转换成符合条件的总记录数countSQL
	 * 
	 * @param sql
	 * @return
	 */
	private String getCountSQL(String sql) {
		// -- countSql=select count(1) from (sql) t 符合条件的总记录数
		return "select count(1) from (" + sql + ") t";
	}

	/**
	 * 将原生SQL转换成pageSQL
	 * 
	 * @param sql
	 * @param pageBean
	 * @return
	 */
	private String getPageSQL(String sql, PageBean pageBean) {
		// (this.page - 1) * this.rows
		// pageSql=sql limit (page-1)*rows,rows
		return sql + " limit " + pageBean.getStartIndex() + "," + pageBean.getRows();
	}
}

BuildTree (complete the conversion of flat data to parent-child level)

package com.zking.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BuildTree {

	/**
	 * 默认-1为顶级节点
	 * @param nodes
	 * @param <T>
	 * @return
	 */
	public static <T> TreeVo<T> build(List<TreeVo<T>> nodes) {

		if (nodes == null) {
			return null;
		}
		List<TreeVo<T>> topNodes = new ArrayList<TreeVo<T>>();

		for (TreeVo<T> children : nodes) {
			String pid = children.getParentId();
			if (pid == null || "-1".equals(pid)) {
				topNodes.add(children);

				continue;
			}

			for (TreeVo<T> parent : nodes) {
				String id = parent.getId();
				if (id != null && id.equals(pid)) {
					parent.getChildren().add(children);
					children.setHasParent(true);
					parent.setChildren(true);
					continue;
				}
			}

		}

		TreeVo<T> root = new TreeVo<T>();
		if (topNodes.size() == 1) {
			root = topNodes.get(0);
		} else {
			root.setId("000");
			root.setParentId("-1");
			root.setHasParent(false);
			root.setChildren(true);
			root.setChecked(true);
			root.setChildren(topNodes);
			root.setText("顶级节点");
			Map<String, Object> state = new HashMap<>(16);
			state.put("opened", true);
			root.setState(state);
		}

		return root;
	}

	/**
	 * 指定idparam为顶级节点
	 * @param nodes
	 * @param idParam
	 * @param <T>
	 * @return
	 */
	public static <T> List<TreeVo<T>> buildList(List<TreeVo<T>> nodes, String idParam) {
		if (nodes == null) {
			return null;
		}
		List<TreeVo<T>> topNodes = new ArrayList<TreeVo<T>>();

		for (TreeVo<T> children : nodes) {

			String pid = children.getParentId();
			if (pid == null || idParam.equals(pid)) {
				topNodes.add(children);

				continue;
			}

			for (TreeVo<T> parent : nodes) {
				String id = parent.getId();
				if (id != null && id.equals(pid)) {
					parent.getChildren().add(children);
					children.setHasParent(true);
					parent.setChildren(true);

					continue;
				}
			}

		}
		return topNodes;
	}

}

ResponseUtil (convert data into json format for echo)

package com.zking.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

public class ResponseUtil {

	public static void write(HttpServletResponse response,Object o)throws Exception{
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		out.println(o.toString());
		out.flush();
		out.close();
	}
	
	public static void writeJson(HttpServletResponse response,Object o)throws Exception{
		ObjectMapper om = new ObjectMapper();
//		om.writeValueAsString(o)代表了json串
		write(response, om.writeValueAsString(o));
	}
}

③ Write entity

Permission (data table entity)

package com.xw.entity;

/**书籍管理系统实体
 * @author 索隆
 *
 */
public class Permission {
private long id;
private String name;
private String description;
private String url;
private long pid;
private int ismenu;
private long displayno;
	
public Permission() {
	// TODO Auto-generated constructor stub
}

public Permission(long id, String name, String description, String url, long pid, int ismenu, long displayno) {
	super();
	this.id = id;
	this.name = name;
	this.description = description;
	this.url = url;
	this.pid = pid;
	this.ismenu = ismenu;
	this.displayno = displayno;
}

public long getId() {
	return id;
}

public void setId(long id) {
	this.id = id;
}

public String getName() {
	return name;
}

public void setName(String name) {
	this.name = name;
}

public String getDescription() {
	return description;
}

public void setDescription(String description) {
	this.description = description;
}

public String getUrl() {
	return url;
}

public void setUrl(String url) {
	this.url = url;
}

public long getPid() {
	return pid;
}

public void setPid(long pid) {
	this.pid = pid;
}

public int getIsmenu() {
	return ismenu;
}

public void setIsmenu(int ismenu) {
	this.ismenu = ismenu;
}

public long getDisplayno() {
	return displayno;
}

public void setDisplayno(long displayno) {
	this.displayno = displayno;
}

@Override
public String toString() {
	return "Permission [id=" + id + ", name=" + name + ", description=" + description + ", url=" + url + ", pid=" + pid
			+ ", ismenu=" + ismenu + ", displayno=" + displayno + "]";
}



}

Note: the type bigint in mysql is long type in java

3.dao layer writing

​
package com.xw.dao;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xw.entity.Permission;
import com.zking.util.BaseDao;
import com.zking.util.BuildTree;
import com.zking.util.TreeVo;

/**书记管理
 * @author 索隆
 *
 */
public class PermissionDao extends BaseDao<Permission>{
	
	/**获取书籍管理的所有信息(平级数据)
	 * @return
	 * @throws Exception 
	 */
	public List<Permission> list() throws Exception{
		String sql="select * from t_easyui_permission";
		return  super.executeQuery(sql, Permission.class, null);
	}

	
	/**将平级数据变成我们需要的父子级数据
	 * @return
	 * @throws Exception 
	 */
	public List<TreeVo<Permission>> menu() throws Exception{
		//存放父子级的容器
		List<TreeVo<Permission>> menu=new ArrayList<TreeVo<Permission>>();
		//拿到平级数据
		List<Permission> list = this.list();
		//遍历平级数据
		for (Permission permission : list) {
			//工具类帮助我们完成父子级关系
			TreeVo<Permission> vo=new TreeVo<Permission>();
			vo.setId(permission.getId()+"");
			vo.setParentId(permission.getPid()+"");
			vo.setText(permission.getName());
			menu.add(vo);
		}
		
		//通过工具类筛选父级菜单的儿子,pid为0是父级菜单
		return BuildTree.buildList(menu, "0");
	}
	
	
	
	public static void main(String[] args) throws Exception {
		//测试数据
		PermissionDao d=new PermissionDao();
	 List<TreeVo<Permission>> menu = d.menu();
	 ObjectMapper om =new ObjectMapper();
	 System.out.println(om.writeValueAsString(menu));
		
		
	}
}

​

We can compare the differences between the two sets of data:

  • flat data
  • parent-child data

4. servlet layer writing

package com.xw.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xw.dao.PermissionDao;
import com.xw.entity.Permission;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.ResponseUtil;
import com.zking.util.TreeVo;

/**书籍管理的servlet处理
 * @author 索隆
 *
 */
public class PermissionAction extends ActionSupport implements ModelDriver<Permission>{
	private Permission Permission=new Permission();
	private PermissionDao pdao=new PermissionDao();
	
	/**初始化书籍管理系统的动态树
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public void listmenu(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		//查询父子级数据
		List<TreeVo<Permission>> menu = pdao.menu();
		//将集合转换成json格式进行回显
		ResponseUtil.writeJson(resp, menu);
	}

	@Override
	public Permission getModel() {
		return Permission;
	}

}

Don't forget to write the configuration file after writing the servlet

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<action path="/blog" type="com.zking.web.BlogAction">
		<forward name="list" path="/blogList.jsp" redirect="false" />
		<forward name="toList" path="/blog.action?methodName=list"
			redirect="true" />
		<forward name="toEdit" path="/blogEdit.jsp" redirect="false" />
	</action>
	

	<!--用户-->
	<action path="/user" type="com.xw.web.Useraction">
	</action>

	<!-- 书籍管理——树 -->
	<action path="/Permission" type="com.xw.web.PermissionAction">
	</action>





</config>

5. jsp page construction

At this time, we can go to the online Layui website to find a satisfactory jsp page

Layui Development and Use Documentation - Getting Started Guide

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE>
<html>
<head>
<%@ include file="common/static.jsp"%>
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
	<div class="layui-layout layui-layout-admin">
		<div class="layui-header">
			<div class="layui-logo layui-hide-xs layui-bg-black">书籍管理系统</div>
			<!-- 头部区域(可配合layui 已有的水平导航) -->
			<ul class="layui-nav layui-layout-left">
				<!-- 移动端显示 -->
				<li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm"
					lay-header-event="menuLeft"><i
					class="layui-icon layui-icon-spread-left"></i></li>
				<!-- Top导航栏 -->
				<li class="layui-nav-item layui-hide-xs"><a href="">nav 1</a></li>
				<li class="layui-nav-item layui-hide-xs"><a href="">nav 2</a></li>
				<li class="layui-nav-item layui-hide-xs"><a href="">nav 3</a></li>
				<li class="layui-nav-item"><a href="javascript:;">nav
						groups</a>
					<dl class="layui-nav-child">
						<dd>
							<a href="">menu 11</a>
						</dd>
						<dd>
							<a href="">menu 22</a>
						</dd>
						<dd>
							<a href="">menu 33</a>
						</dd>
					</dl></li>
			</ul>
			<!-- 个人头像及账号操作 -->
			<ul class="layui-nav layui-layout-right">
				<li class="layui-nav-item layui-hide layui-show-md-inline-block">
					<a href="javascript:;"> <img
						src="//tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg"
						class="layui-nav-img"> tester
				</a>
					<dl class="layui-nav-child">
						<dd>
							<a href="">Your Profile</a>
						</dd>
						<dd>
							<a href="">Settings</a>
						</dd>
						<dd>
							<a href="login.jsp">Sign out</a>
						</dd>
					</dl>
				</li>
				<li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
					<a href="javascript:;"> <i
						class="layui-icon layui-icon-more-vertical"></i>
				</a>
				</li>
			</ul>
		</div>

		<div class="layui-side layui-bg-black">
			<div class="layui-side-scroll">
				<!-- 左侧导航区域(可配合layui已有的垂直导航) -->
				<ul id="menu" class="layui-nav layui-nav-tree" lay-filter="menu">
					<!-- <li class="layui-nav-item layui-nav-itemed">
          <a class="" href="javascript:;">menu group 1</a>
          <dl class="layui-nav-child">
            <dd><a href="javascript:;">menu 1</a></dd>
            <dd><a href="javascript:;">menu 2</a></dd>
            <dd><a href="javascript:;">menu 3</a></dd>
            <dd><a href="">the links</a></dd>
          </dl>
        </li>
        <li class="layui-nav-item">
          <a href="javascript:;">menu group 2</a>
          <dl class="layui-nav-child">
            <dd><a href="javascript:;">list 1</a></dd>
            <dd><a href="javascript:;">list 2</a></dd>
            <dd><a href="">超链接</a></dd>
          </dl>
        </li>
        <li class="layui-nav-item"><a href="javascript:;">click menu item</a></li>
        <li class="layui-nav-item"><a href="">the links</a></li> -->
				</ul>
			</div>
		</div>

		<div class="layui-body">
			<!-- 内容主体区域 -->
			<div style="padding: 15px;">内容主体区域。记得修改 layui.css 和 js 的路径</div>
		</div>

		<div class="layui-footer">
			<!-- 底部固定区域 -->
			底部固定区域
		</div>
	</div>
	<script>
//JS 
layui.use(['element', 'layer', 'util'], function(){
  var element = layui.element
  ,layer = layui.layer
  ,util = layui.util
  ,$ = layui.$;
  

  	$.ajax({
  		url: "${pageContext.request.contextPath}/Permission.action?methodName=listmenu",
  		type: 'post',
  		dataType: 'json',
  		success: function(data) {
  			//定义一个变量将回显的数据进行拼接,最终追加到指定标签上
  			var str='';
  			$.each(data,function(i,n){
  				str+='<li class="layui-nav-item layui-nav-itemed">';
  				str+=' <a class="" href="javascript:;">'+n.text+'</a>';
  				//判断有无children节点有就遍历
  				if(n.hasChildren){
  					//有children节点拿到children节点
  					var children=n.children;
  						str+='<dl class="layui-nav-child">';
  					$.each(children,function(idx,node){
  						str+='<dd><a href="javascript:;">'+node.text+'</a></dd>';
  		  			})
  		  				str+='</dl>';
  				}
  				
  				str+='</li>';
  				
  			})
  			//将拼接内容追加到指定ul标签
  			$("#menu").html(str);
  			
  			element.render('menu');
  			
  		}
  	})
  
  
});
</script>
</body>
</html>

Tips:

 The usefulness of element.render():

Assuming you are using a specific front-end framework or library, where `element` is the corresponding component or object, call the `render()` method. Generally speaking, the `render()` method is used to render components or elements to specific positions in the web page. The specific functions are as follows:

  • 1. Rendering components: `render()` method is used to render specific components to the page. It will parse the content and style of the component to generate the corresponding HTML structure, and make it visible in the browser.
  • 2. Update the page: If the component or element already exists and is displayed on the page, calling `render()` again can trigger the update of the page. This is useful when you need to update the page based on changes in data.
  • 3. Binding events: When rendering a component, the `render()` method usually binds the event of the component to the corresponding DOM element. This ensures that when the user interacts with the component, the component responds appropriately.
  • It should be noted that the specific implementation and usage of the `render()` method depends on the front-end framework or library used, and there may be additional parameters and options. To understand exactly what the `render()` method does, please refer to the documentation and usage guide for the respective framework or library.

6. Case presentation

My sharing is over here, welcome to the comment area to discuss and communicate! !

If you find it useful, please give it a like, love ♥ ♥

Guess you like

Origin blog.csdn.net/weixin_74318097/article/details/131677155