search
HomeWeb Front-endJS TutorialHow to use Vue to develop time conversion instructions?

How to use Vue to develop time conversion instructions?

Jun 11, 2018 pm 04:15 PM
vueTime conversion

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:&#39;#app&#39;,
  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 ? &#39;0&#39; + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? &#39;0&#39; + date.getDate() : date.getDate();
        return date.getFullYear() + &#39;-&#39; + month + &#39;-&#39; + 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 = &#39;&#39;;

        if(timer <= 0){
          tip = &#39;刚刚&#39;;
        }else if(Math.floor(timer/60) <= 0){
          tip = &#39;刚刚&#39;;
        }else if(timer < 3600){
          tip = Math.floor(timer/60) + &#39;分钟前&#39;;
        }else if(timer >= 3600 && (timestamp - today >= 0)){
          tip = Math.floor(timer/3600) + &#39;小时前&#39;;
        }else if(timer/86400 <= 31){
          tip = Math.ceil(timer/86400) + &#39;天前&#39;;
        }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(&#39;time&#39;,{
  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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

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),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor