Vue uses a function for every page, but I don't want to introduce it one by one

A timestamp function is used on many pages

//HTML
{{ scope.row.createTime|formatDate }}

//js
import {formatDate} from "@/assets/js/date.js"

//
filters:{
    formatDate(time) {
        var date = new Date(time);
        return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    },
}

every time this page needs to use a timestamp, I will copy the code over, which is very troublesome. Is there a good solution?


there are many ways to choose according to what you think is the best way.
can use either a global filter or a global blend.
if you are not familiar with either of these, or if you are not sure how to use them, you can write the code you need into a util tool, that is, a util.js file.

export default {
  formatDate(time){
    
  }
}

then mount it to the global in main.js:

Vue.prototype.$utils = utils;

then, just use it where you need it.

this.$utils.formatDate(time)

Vue.mixin global mixing


global filter


scheme 1, backend formatted time
scheme 2, since a filter is used, why not use a global filter? ide/filters.html" rel=" nofollow noreferrer "> vue document: filter


  1. mixin
  2. extend
  3. Vue.filter

use the global filter


can also do this by binding the function to the vue prototype in main.js.

Vue.prototype.formatDate=(time)=>{
    var date = new Date(time);
    return formatDate(date, 'yyyy-MM-dd hh:mm:ss');
    }

Register global filters in main.js

Vue.filter('formatDate', function(time){
  var date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss');
        })

use the global method on the official website

main.jsGlobal.js

filter

demo

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b32268-2b63b.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b32268-2b63b.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?