Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

javascript - vuejs - can't get dayjs working in browser

I'm trying to show dates diffForHumans based on this guide: https://www.talvbansal.me/blog/human-readable-dates-with-dayjs-in-vue-js/

So I'm trying to load DayJS as component in my VueJS app this way:

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

Then I'm getting this error:

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

Am I doing something wrong?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

Your issue is two fold:

  1. dayjs is not a VueJS component, so it does not make sense to use Vue.component("dayjs", dayjs); on it
  2. You did not have the required dependencies for .fromNow() to work:

Pro tip: Make sure you read the documentation of plugins that you're using. They often contain all the proof-of-concept code and instructions to get things up and running. Here is a proof-of-concept example:

// 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...