Having trouble getting dayjs to work in the browser with Vue.js?

Trying to display date differences in a human-readable format using the guide found here:

I'm attempting to incorporate DayJS as a component in my VueJS application like this:

<script src="{{ asset('/vendor/vuejs/vue.js') }}" type="text/javascript"></script>
<script src="{{ asset('/vendor/vue-dayjs/dayjs.min.js') }}"></script>
<script type="text/javascript">

  Vue.component("dayjs", dayjs);

  Vue.filter('formatDateDiffForHumans', function(value){
    if (!value) return null;
    return dayjs(value).fromNow();
  });

  var app = new Vue({
    el:'#vue_app',
    data:{
      ......
    }
  });

</script>

.....

<span>@{{ t.object.created_at | formatDateDiffForHumans }}</span>

However, upon implementation, I encountered the following error:

[Vue warn]: Error in render: "TypeError: dayjs(...).fromNow is not a function"

What could be causing this issue?

Answer №1

Your problem has two components:

  1. The use of dayjs as a VueJS component is not supported, so the syntax
    Vue.component("dayjs", dayjs);
    does not apply here.
  2. You are missing essential dependencies for the .fromNow() function to function properly:
    • To utilize the RelativeTime plugin that is mentioned in the documentation, please refer to the relevant section.
    • Extend the capabilities of dayjs with specific plugins by using commands like
      dayjs.extend(window.dayjs_plugin_relativeTime);

Key advice: Always thoroughly review the documentation provided for any plugins you intend to incorporate into your project. The resources usually include code examples and detailed instructions to assist you in setting everything up correctly. Here's an example to get you started:

// Extend DayJS with plugin
dayjs.extend(window.dayjs_plugin_relativeTime);

Vue.filter('formatDateDiffForHumans', function(value) {
  if (!value) return null;
  return dayjs(value).fromNow();
});

var app = new Vue({
  el: '#vue_app',
  data: {
    myDate: new Date(2018, 8, 18)
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.3/dayjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.3/plugin/relativeTime.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue_app">
  <span>@{{ myDate | formatDateDiffForHumans }}</span>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble decoding JWE using the NPM Jose library

Although I can successfully decrypt a JWE using an older version of jose, I'm facing difficulties in utilizing the latest version API. The headers of my token are as follows: { "alg": "A128KW", "enc": "A128CBC-H ...

Discover the power of lodash's .groupBy method as you learn how to efficiently group objects within another

Utilizing lodash's _.groupBy function, I have generated the following data: { "Generic Drugs":[ { itemDes: "Dulcolax", itemGeneric: "Bisacodyl", pr ...

Customizing active-class in Vuetify

How do I customize the appearance of my v-list-item-group when it is in the active state? <v-list> <v-list-item-group v-model="day" color="green"> <v-list-item v-for="(item, i) in items" :key="i"> <v-list-item-content& ...

What is the best way to run multiple functions from an object?

My goal is to call all the functions that are contained within an object. const data = { fruits: funcA(), vegetables: funcB(), bread: funcC(), } The desired result looks like this: firstFunc(); dispatch(funcA()); dispatch(funcB()); dispatch(funcC() ...

"Why is it that the keypress event doesn't function properly when using the on() method

My goal is to capture the enter event for an input field $("input[name='search']").on("keypress", function(e){ if (e.which == '13') { alert('code'); } }); This is the HTML code snippet: <input name="searc ...

What is the process for validating a JWT token using an x.509 certificate in a Node.js environment?

I need assistance with making a node script capable of validating a JWT token. I possess the public key, which is an x.509 certificate, along with the JWT itself. My attempt to utilize https://github.com/auth0/node-jsonwebtoken proved unsuccessful as it d ...

Troubleshooting unexpected issues with dynamically updating HTML using innerHTML

Need help with a renderWorkoutUpdated function that replaces specific workout records with updated values. _renderWorkoutUpdated(currentWorkout) { let html = `<li class="workout workout--${currentWorkout.type}" data-id="${ curre ...

The width of the Bootstrap row decreases with each subsequent row

I'm having trouble understanding this issue, as it seems like every time I try to align my rows in bootstrap, they keep getting smaller. Can anyone point out what mistake I might be making? ...

Tips for using the $each() function within a jquery append to retrieve object-based conditions for parameters

I encountered an issue while trying to include a condition in my endpoint, and I have recently started using jQuery for this purpose. Here is the code snippet from my Laravel view: <tbody id="tbody"> @foreach ($modul as $m) <tr> ...

Discover the technique of accessing HTML/CSS toggle switch value in Golang

I am attempting to incorporate a toggle switch into my webpage. I followed this specific tutorial for guidance: w3schools.com Currently, I have set up my HTML file with a button and the toggle switch. Additionally, I configured my web server in Go to lis ...

Exploring the connections between data in Laravel and Vue to provide insightful displays

I am currently facing an issue with displaying data from a many-to-many relationship in my Vue component. After fetching user data from a REST API, I store it in an object like this: users: {}, //... axios.get("api/user").then(({data}) => (this.users ...

Using a for loop in JavaScript to dynamically generate HTML content within a Django project

Do you have a unique question to ask? Version: Django version 3.0.8 This block contains my JavaScript code: fetch(`/loadbox/${message.id}`) .then(response => response.json()) .then(dialog => { let detailcontent= `<div class=" ...

What steps can I take to direct mobile visitors to the mobile-friendly version of my website?

Looking for a way to automatically redirect users on mobile devices from www.domain.com to the new mobile version at m.domain.com? ...

Encountering a Vue and Supabase error during the NPM run npm process

I recently encountered an issue with my Vue application that I have been working on. Initially, everything was running smoothly until I decided to integrate a backend using Supabase and deploy the app on Vercel. However, after adding the backend components ...

Accessing arrays using bracket notation

When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation: object.property object['property'] Let's explore a scenario using the latter method: const user = ...

Error in Node.js child_process: unable to access the property '_writableState' as it is undefined

I'm currently working on integrating ffmpeg's functionality into a Node.js API by utilizing the child_process library. However, I encounter an error when trying to pass data to ffmpeg's stdin pipe, specifically getting a TypeError: Cannot re ...

Passing data retrieved from Laravel to AJAX using the ID

I'm currently struggling to figure out the best approach for handling a multiple comment form. Here is an example of what my form looks like: @foreach($lists as $list) //some views <form class="commentForm"> <input type="te ...

I am struggling to find the correct way to fetch images dynamically from Cloudinary and display them as backgrounds. How should I go about implementing this feature successfully

I have been trying to figure out why I am unable to retrieve the image from cloudinary. My goal is to use the image as a background when posting, but it seems like I am not fetching the image correctly. function Post({post}){ return( <div ...

The reason for setting a variable as void 0 in JavaScript

Currently, I am delving into the libraries referenced in this particular article as well as other sources. There are some truly mind-boggling concepts contained within these resources, one of which is highlighted by the following line: var cb = void 0; I ...

Is there a way to replicate the ctrl-F5 function using jQuery?

Is there a way to use jQuery to refresh the page and clear the cache at the same time? ...