Let’s implement such a Vue custom instruction v-time to convert the timestamp passed in the expression into relative time in real time. Below I bring you a real-time time conversion instruction using Vue. Friends who need it can refer to it
Preface
Recently In other words, if you see a certain function of a website, you can probably guess what the business logic behind it is, and if you can develop an identical function, then your front-end skills are considered to be advanced. Advanced level. For example, the topic we are going to talk about today: How to use Vue to develop a real-time time conversion instruction?
The next text starts from here~
As shown in the picture above (I intercepted part of the home page of a technical community), you can see that using Check the time text with a red border. When many websites publish updates, there will be a relative time converted from the local time. So do you know the principle behind the implementation of this function? If you are interested, please prepare melon seeds and tea and continue reading.
Generally, the storage time format on the server is Unix timestamp. For example, the timestamp of 2018-01-17 06:00:00 is 1516140000. After the front end gets the data, it converts it into a sustainable time format and then displays it. In order to show real-time, in some social products, it will even be converted in real time into different formats such as seconds ago, minutes ago, hours ago, etc., because this is better than directly converting into years, months, days, hours, minutes, etc. In seconds, it appears more user-friendly and the experience is more humane.
Today, we will implement such a Vue custom instruction v-time to convert the timestamp passed in the expression into relative time in real time. In order to facilitate the demonstration effect, we defined two times during initialization.
First look at the html structure:
<p id="app" v-cloak> <p v-time="timeNow"></p> <p v-time="timeBefore"></p> </p>
and initialize a Vue instance:
var app = new Vue({ el:'#app', data:{ timeNow:(new Date()).getTime(), timeBefore:686219755822 } })
timeNow is the current time, timeBefore is a hard-coded time: 1991-09- 30.
Let’s first analyze the logic of time conversion:
1 minute ago, “just now” was displayed.
Between 1 minute and 1 hour, "xx minutes ago" is displayed.
Between 1 hour and 1 day, "xx hours ago" is displayed.
Between 1 day and 1 month (31 days), "xx days ago" is displayed.
If it is greater than 1 month, it will display "xx year xx month xx day".
Listed in this way, the logic will be clear at a glance. In order to make the judgment simpler, we uniformly use timestamps for size judgment here. Before writing the instruction v-time, we need to write a series of time-related functions. We declare an object Time and encapsulate them all in it.
var Time = { //获取当前时间戳 getUnix:function(){ var date = new Date(); return date.getTime(); }, //获取今天0点0分0秒的时间戳 getTodayUnix:function(){ var date = new Date(); date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); return date.getTime(); }, //获取今年1月1日0点0分0秒的时间戳 getYearUnix:function(){ var date = new Date(); date.setMonth(0); date.setDate(1); date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); return date.getTime(); }, //获取标准年月日 getLastDate:function(time){ var date = new Date(time); var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1; var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); return date.getFullYear() + '-' + month + '-' + day; }, //转换时间 getFormatTime:function(timestamp){ var now = this.getUnix(); // 当前时间戳 var today = this.getTodayUnix(); // 今天0点的时间戳 var year = this.getYearUnix(); // 今年0点的时间戳 var timer = (now - timestamp) / 1000; // 转换为秒级时间戳 var tip = ''; if(timer <= 0){ tip = '刚刚'; }else if(Math.floor(timer/60) <= 0){ tip = '刚刚'; }else if(timer < 3600){ tip = Math.floor(timer/60) + '分钟前'; }else if(timer >= 3600 && (timestamp - today >= 0)){ tip = Math.floor(timer/3600) + '小时前'; }else if(timer/86400 <= 31){ tip = Math.ceil(timer/86400) + '天前'; }else{ tip = this.getLastDate(timestamp); } return tip; } }
Of course, if you don’t know much about JavaScript’s Date type, you can first go to runoob.com to learn more.
Then, the Time.getFormatTime() method is required for the custom instruction v-time. The parameter is a millisecond timestamp and returns the organized time format. String.
Finally, let’s see how we use Vue to customize an instruction v-time:
Vue.directive('time',{ bind:function(el, binding){ el.innerHTML = Time.getFormatTime(binding.value); el.__timeout__ = setInterval(function(){ el.innerHTML = Time.getFormatTime(binding.value); }, 60000) }, unbind:function(el){ clearInterval(el.__timeout__); delete el.__timeout__; } })
In the bind hook, pass the value of the instruction v-time expression binding.value as a parameter Get the formatted time in the Time.getFormatTime() method, and write the element where the instruction is located through el.innerHTML. The timer el.__timeout__ is triggered every minute, updates the time, and is cleared in the unbind hook.
You may ask, what is this binding.value?
Of course, you can print it on the console through the console.log(binding) method, and it will be clear at a glance.
Here, let me first add that the options for custom instructions are composed of several hook functions, including bind, insert, update, componentUpdated, and unbind. The bind and unbind are only called once. Each hook function has several parameters available, such as el and binding we used above.
The elements bound to the el directive can be used to directly manipulate the DOM. Binding is an object that contains many attributes, as shown in the figure above:
name: Instruction name
rawName: Custom instruction
value: The binding value of the instruction
expression: The string form of the binding value
modifiers: an object containing modifiers
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to implement page jump in vue and return to the initial position of the original page
Cooperate in vue-router How ElementUI implements navigation
Detailed explanation of introducing elementUI components into the vue project
Refresh and tab switching in vue
How to implement mouse-responsive Taobao animation effect in jQuery
jQuery Implemented mouse response buffer animation effect
The above is the detailed content of How to use Vue to develop time conversion instructions?. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools