(Framework7 mobile webapp) Springboot introductory training 8 Component template MVVM and AJAX

In webapp development framework 7, the most commonly used is the development of MVVM mode using Component template. This mode uses template technology and ajax and dmo7 (similar to jquery) to generate page html. It requires developers to have high ability to use js script.
The Component template requires the componentUrl attribute in the route to define the template access address.

routes = [
  {
    path: '/Routing path/',
    componentUrl: 'Template html Page address url',
];

1 Component template composition

The Component template is divided into three parts

  • template html element layer
  • style css style layer
  • script layer

Component.html composition

<template>
  <div class="page" >
    HTML content
  </div>
</template>
<style>
  .red-link {
    color: red;
  }
    CSS style
</style>
<script>
  // component module syntax mvvm pattern html page elements are bound to the data model
  // 1. Parameters passed in by props
  // 2. fk7 built-in object of operation
  export default (props, {}) => {

    return $render;
  }
</script>

1 template

template contains all Framework7 UI component elements, and can also be other html elements. All page elements should be in the class="page" element.

<template>
  <div class="page">
    html page
  </div>
</template>

All elements in the template must have < / > to indicate the end. Cannot end with < br / > < input type = "" / > < img Src / >.

Element end example

<template>
<!-- This closure is correct -->    
< input type="" ></input> 
<br></br>
<div>element</div>
<!-- This shutdown is wrong -->    
<br/>
< input type="" />
</template>

2 style

Define page css styles and inline styles.

<style>
  .red-link { 
    color: red;
  }                                    
</style>

3 script

The most important part of the script is the default function of the template. We need to use this default function to control all html elements of the whole template page, custom events, connecting background data, parameter conversion and other functions.

export default (props, {}) => {
	return $render;
}

1 define the default function body export default (props, {context parameter}) = > {return $render;}

  • props parameters, parameters accessed by the router, are generally unavailable
  • Context parameters communicate the built-in parameters of the context
  • $render returns the tag template text with the HTML content of the component

4 parameters and events in the default function

Parameters [attribute, array, object] can be defined in the default function, and the defined parameters can be bound to html elements using the ${name} method in the template layer.

  • Parameter type let the default attributes in the function are let
<template>
<div class="page" th:inline="text">
<div class="page-content">
 <p>${value}</p>    <------------------|
    </div>                             |
  </div>                               |
</template>                            |
<style>                                |
  .red-link {                          |
    color: red;                        |
  }                                    |
</style>                               |
<script th:inline="javascript">        |
  export default (props,{}) => {       |
    let value = 'First program';------------|
   })
    return $render;
  }
</script>
  • array define

    Define the let names = [] array object, and use the template markup language to cycle through the array contents in the template template.

<template>
<div class="page" th:inline="text">
<div class="page-content">
<div class="list simple-list">
<ul>//Template language cycle displays data content
  ${names.map((name) => $h`    <----------|
    <li >${name.id}${name.name}</li>      |
   `)}                                    |
 </ul>                                    |
</div>                                    |
</div>                                    |
</div>                                    |
</template>                               |
<script th:inline="javascript">           |
//The mvvm pattern binds html page elements to the data model|
  export default (props,                  |
                  {$update}) => {         |
    let names=[     <---------------------|
        {name:'1 Records',id:1},
        {name:'2 Records',id:2},
        {name:'3 Records',id:3}]
    return $render;
  }
</script>
  • Event definition and binding

    Define the event method in the default function, and then bind the event to the corresponding html element through the @ click tag in the template template.

<template>
<div class="page" th:inline="text">
<div class="page-content">
<div class="list simple-list">
<ul>//Template language cycle displays data content
  ${names.map((name) => $h`   
    <li @click=${onfind}>      <----------|   
    ${name.id}${name.name}</li>           |
   `)}                                    |
 </ul>                                    |
</div>                                    |
</div>                                    |
</div>                                    |
</template>                               |
<script th:inline="javascript">           |
//The mvvm pattern binds html page elements to the data model|
  export default (props,                  |
                  {$update}) => {         |
   //Custom event|
   const onfind=(e)=>{   <----------------|
       console.log(e.target);
       alert(e.target);
    };                 
      let names=[ 
        {name:'1 Records',id:1},
        {name:'2 Records',id:2},
        {name:'3 Records',id:3}]
    return $render;
  }
</script>

@Equivalent to on in event

eventquote
onclick()@click
onchange()@change
onsubmit()@submit
onblur()@blur
onfocus()@focus

2. Built in function parameters

The default function in the template comes with many powerful parameters. Developers use these parameters to operate the html elements and script events of the template page. These parameters can be freely combined according to business requirements.

export default (props, {Parameter 1, parameter 2}) => {
	return $render;
}

$on page event

The $on parameter is a component event, which is usually used to handle template initialization events.

export default (props,{$on}) => {
  $on('pageMounted', (e, page) => {
    //Event triggered when generating a page
  });
  $on('pageInit', (e, page) => {
    //Template page initialization event
  });
  $on('pageBeforeIn', (e, page) => {
    //Before dom generation
  });
  $on('pageAfterIn', (e, page) => {
    //Page creation view
  });
  $on('pageBeforeOut', (e, page) => {
     //After page dom generation
  });
  $on('pageAfterOut', (e, page) => {
     //After the page view is created
  });
  $on('pageBeforeUnmount', (e, page) => {
   //Before uninstalling the page
  });
  $on('pageBeforeRemove', (e, page) => {
    //After unloading the page
  });
	return $render;
}

$Dom7 Library

$is the Dom7 library js reference object of Framework7. You can use the functions of Dom7 in the default function.

export default (props,{$}) => {
    	//See the same jquery as Dom7 api 
        $('p').text('Welcome to app page')
    	return $render;
}

$h template object

Template language object, which can generate html pages. If you reference the $h object in the template, you can write html elements in the template object.

export default (props,{$}) => { 
return () => $h`
    <div class="page">
      <ul>
        ${list.map((item) => $h`
          <li>${item}</li>
        `)}
      </ul>
    </div>`
}

You can also generate templates in the template element

<template>
<div class="page" th:inline="text">
<div class="page-content">
${user && $h`
   <div class="list simple-list">
    <ul>
      <li>name: ${user.name}</li>
      <li>character: ${user.sex}</li>
      <li>Age: ${user.age}</li>
    </ul>
  </div>
`}
</div>
</div>
</template>

$f7 Framework7 object

$f7 is a Framework7 object reference through which you can create and control Framework7 UI components.

export default (props,{$,$f7}) => {
    //Framework7 object reference
	$f7.dialog.alert('Popup ')
    return $render;
}

$f7router routing object

$f7router is the route reference object in the rectification component. For routing use, refer to Chapter 2 routing use.

export default (props,{$,$f7,$f7router}) => {
    //Use routing method
	$f7router.back();
    return $render;
}

$el html element object

Parameter object passed The value attribute contains the object of the Dom7 instance of the HTML element in the template component$ el.value needs to be used after the component is generated.

export default (props,{$el}) => {
    //Get html element object
	$el.value.find('p').addClass('red')
    return $render;
}

$store script cache

$store is the cache function of scripts. You can save the used data in this cache.

const store = createStore({
  user: {
    userid: 10,
  }
});
---------- Template page --------
export default (props,{$store}) => {
    //Get html element object
    const users = $store.user.userid;
	alert(  const users = $store.getters('users'););
    return $render;
}

$update template update

When the template html element changes, you need to call this method to refresh the whole template page. Very important method, if it does not refresh, the html elements in the page will not be regenerated. It is understood that $update() is required for every data change in mvvm mode; Rebind once.

<template>
<div class="page" th:inline="text">
<div class="page-content">
 <p>${telte}</p>    <------------------|  Show second time
    </div>                             |
  </div>                               |
</template>                            |
<script th:inline="javascript">        |
export default (props,                 |
				{$on,$update}) => {    |
  let telte='for the first time';   <-------------- |
  $on('pageInit', (e, page) => {       |
    telte='The second time';     <-------------- | 
    //Page data change
    $update();
  });
}
</script>

3 mixed with Thymeleaf

In the Controller container class that accesses the Thymeleaf page, you can define parameters into the Model map. By binding the html page element to the Thymeleaf template tag, we pass the parameters defined in the Controller container to the template page.

For example, set a parameter "title" in the method and save it to the request. spring boot is map AddAttribute method. We get this parameter through the Thymeleaf tag in the Component page.

Controller container method

@RequestMapping("/routes3")
public String routes3(Model map) {
	map.addAttribute("title", "This is brother Tao's first program");
	return "app/Component";
}

Component.html

<template>
 <!-- Thymeleaf Template definition binding th:inline="text" element  -->
<div class="page" th:inline="text">
<div class="page-content">
 <!-- Backstage title Element direct binding  -->   
 <p>[(${title})]</p>
 <p>${value}</p>
    </div>
  </div>
</template>
<!-- component styles -->
<style>
  .red-link {
    color: red;
  }
</style>
<!-- Thymeleaf Template definition binding th:inline="javascript"  -->
<script th:inline="javascript">
  export default (props,{}) => {
 //Bind the background parameter title to the value in the function, and the value is bound to the html template page through the template
    let value = '[(${title})]';
   })
    return $render;
  }
</script>
  • Add th:inline = "text" binding Thymeleaf tag to the template page element
  • Add th:inline = "javascript" binding Thymeleaf tag to the script element

How to distinguish Thymeleaf tags from Component template tags

[(${element})] Thymeleaf tag

${element} Component template label

4 Ajax request usage

The method of mixing the template with Thymeleaf to obtain background data information was introduced earlier, but this method is very inconvenient to use in mvvm mode. You can use ajax to obtain background json for data interaction, which is very convenient to use in mvvm mode$ f7 refers to the Ajax request Library of framework 7, which can directly access XHR requests (Ajax).

Define the Spring boot json method

@RestController()
@RequestMapping("/FK7")
public class Fk7Conteroller {
	@RequestMapping("/list")
	public List getList1(){
		List list=new ArrayList();
		Map map=new HashMap();
		map.put("id", "1");
		map.put("name", "Title I***********");
		Map map1=new HashMap();
		map1.put("id", "2");
		map1.put("name", "Title II***********");
		list.add(map);
		list.add(map1);
		return list;
	}	
}
  • In the template default function, the ajax method in the $f7 parameter is invoked to access the json method container in spring boot.

ajax request url

<template>
<div class="page" th:inline="text">
<div class="page-content">
<div class="list simple-list">
  <ul>
    ${user && user.map((u1) => $h`
      <li>${u1.id}${u1.name}</li>
   `)}
  </ul>
</div>
</div>
</div>
</template>
<script th:inline="javascript"> 
export default (props, 
		{$f7, $on, $update}) => {
	let title = '';
    let user = [];
    $on('pageInit', () => {
      //ajax get spring boot json string
	  $f7.request.get('./FK7/list').
      then((res) => {
        //Convert string to json object
		user = eval("("+ res.data+")");
		$update();
	  });
    })
    return $render;
  }
</script>

ajax returns a string and turns it into a json object

  • eval("("+ res.data+")"); Use the eval method to convert the string returned by ajax into a json object

1 app.request.get request method

Load data from the server using HTTP GET requests

app.request.get( url , data , success , error , dataType )
//example
app.request.get('./FK7/list',{ name: 'user', id:5 },
     function(data, status, xhr){
    //Access success return method
     alert(data);
    },function(xhr, status, message){
      //Access error return method
    },'json');
// Use the then method to handle the return method
app.request.get('./FK7/list',{ name: 'user', id:5 })
    .then(function (res) {
    console.log(res.data);
 });
  • url - String - Request url
  • data request parameters.
  • success - function (data, status, xhr) - the callback function executed when the request is successful.
  • error - function (xhr, status, message) - callback function executed when the request fails.
  • dataType server protocol type. It could be text or json.

2 app.request.post request method

Load data from the server using HTTP POST requests

app.request.post( url , data , success , error , dataType )
app.request.post('./FK7/list',{ name: 'user', id:5 },
     function(data, status, xhr){
    //Access success return method
     alert(data);
    },function(xhr, status, message){
      //Access error return method
    },'json');
// Use the then method to handle the return method
app.request.post('./FK7/list',{ name: 'user', id:5 })
    .then(function (res) {
    console.log(res.data);
 });
  • url - String - Request url
  • data request parameters.
  • success - function (data, status, xhr) - the callback function executed when the request is successful.
  • error - function (xhr, status, message) - callback function executed when the request fails.
  • dataType server protocol type. It could be text or json.

3 app.request.json request method

Use the GET HTTP request to load JSON encoded data from the server

app.request.json ( url , data , success , error)
app.request.json ('./FK7/list',{ name: 'user', id:5 },
     function(data, status, xhr){
    //Access success return method
     alert(data);
    },function(xhr, status, message){
      //Access error return method
    });
// Use the then method to handle the return method
app.request.json('./FK7/list',{ name: 'user', id:5 })
    .then(function (res) {
    console.log(res.data);
 });
  • url - String - Request url

  • data request parameters.

  • success - function (data, status, xhr) - the callback function executed when the request is successful.

  • error - function (xhr, status, message) - callback function executed when the request fails.

4 app.request.postJSON request method

Send JSON data using HTTP POST request

app.request.postJSON ( url , data , success , error)
app.request.postJSON ('./FK7/list',{ name: 'user', id:5 },
     function(data, status, xhr){
    //Access success return method
     alert(data);
    },function(xhr, status, message){
      //Access error return method
    });
// Use the then method to handle the return method
app.request.postJSON('./FK7/list',{ name: 'user', id:5 })
    .then(function (res) {
    console.log(res.data);
 });
  • url - String - Request url
  • data request parameters.
  • success - function (data, status, xhr) - the callback function executed when the request is successful.
  • error - function (xhr, status, message) - callback function executed when the request fails.

5 general method of request (options)

With complex ajax requests, you need to use a common method to send requests to services

  • request(options) parameter
//Main function reference
var app = new Framework7({ });
app.request({
  url:'./FK7/list'
}).then(function (res) {
    alert(res.data);
});

Common parameters

Attribute nameexplain
urlRequest URL
asyncSet this option to false for synchronous or asynchronous requests
methodRequest method (e.g. "POST", "GET", "PUT")
cacheIf set to false, it forces the requested page not to be cached by the browser. Setting the cache to false applies only to HEAD and GET requests
contentTypeRequest protocol multipart / form data or text/plain. For cross domain requests, set the content type to application/x-www-form-urlencoded, multipart / form data, or text/plain
crossDomainThe request (such as JSONP) is enforced across domains, and the value is set to true. When true, the X-Requested-With: XMLHttpRequest request header will not be added to the request
dataparameter
processDataFor the default content type "application/x-www-form-urlencoded", please set this option to false
dataTypeReturn data type text or json
headersRequest header key / value pair setting
successfunction (data, status, xhr) accessed successfully
errorfunction (xhr, status, message) error method
  • Pass the parameter into the method for calling

Call example

app.request({
  url:'./FK7/list',
  async:true,
  contentType:'text/plain',
  success:function(data, status, xhr){
    alert(data);
	}
})

6 then and catch methods

You can use then as the access success method and catch as the access failure callback method.

app.request.postJSON('./FK7/list',{name: 'user',id:5 })
.then(function (res){
   list=res.data;
   $update();
}).catch(function (err) {
   list=[];
   $update();
    console.log(err.xhr)
    console.log(err.status)
    console.log(err.message)
});

5 comprehensive application of Ajax and Component MVVM

Controller container method

@RestController()
@RequestMapping("/FK7")
public class Fk7Conteroller {
	@RequestMapping("/list")
	public List getList1(){
		List list=new ArrayList();
		Map map=new HashMap();
		map.put("id", "1");
		map.put("name", "Title I   ***********");
		Map map1=new HashMap();
		map1.put("id", "2");
		map1.put("name", "Title II   ***********");
		list.add(map);
		list.add(map1);
		return list;
	}	
}

Template HTML

<template>
<div class="page" th:inline="text">
<div class="page-content">
<div class="list simple-list">
   <ul>
     ${user && user.map((u1) => $h`
            <li>${u1.id>1?'a':'b'}${u1.name}</li>
     `)}
    </ul>
</div>
</div>
</div>
</template>
<style>
</style>
<script th:inline="javascript">
  // component module syntax mvvm pattern html page elements are bound to the data model
export default (props, {$, $f7, $on, $update}) => {
let user = [];
    $on('pageInit', () => {
       $f7.request.get('./FK7/list').then((res) => {
          user = eval("("+ res.data+")");
          $update();
       });
    })
    return $render;
}
</script>

$h tips

$h cycle

${user && user.map((u1) => $h`
  <li>${u1.name}</li>
`)}
  • user. Map ((U1) = > template circulation function

$h judge nesting

${user && user.map((u1) => $h`
   ${u1.id>1 && $h`
	 <li>${u1.id>1?'a':'b'}${u1.name}</li>
   `}
`)}
  • You can nest judgment in the template loop. As long as you reference the template and reference the $h object, you can write html elements in the template object.

Get event @ click parameter

The event < Li @ Click = ${onFind} > defined in the template can only obtain the event source parameter, and other event parameters cannot be obtained in the event. How can we solve this problem? Change the parameter into an element attribute, save it in the element, turn it into a dm7 object through the event source, and take out the attribute in the element.

<div class="list simple-list">
 <ul>
${user && user.map((u1) => $h`
 <li id="${u1.id}" 
     name="${u1.name}"  
     @click=${onFind}>
     ${u1.id}${u1.name}
     </li>
`)}
 </ul>
</div>
<script th:inline="javascript">
export default (props, 
                {$, $f7,$on,$update}) => {
 const onFind=(e)=>{
   //e. html content of the element of the target event
   console.log(e.target);
   //Gets the attribute object value of the element
   alert($(e.target).attr("id"));
 }
 return $render;
}
</script>


  • li element defines two attribute parameters: ID and name
  • The @ click event is defined in the li element
  • Events defined in default functions

The event object e.target obtains the html content of the event element.

Put the e.target object into the dom7 object and get the other element attribute object $(e.target) attr(“id”).

Baidu network disk download address
Link: https://pan.baidu.com/s/1rDpcZtdBA6i7vBmYTMwcUA
Extraction code: 1234
Download address Run code download

Keywords: Java JQuery Ajax

Added by kenle on Mon, 20 Dec 2021 16:00:40 +0200