Vue registers the global method. What if you can't get it when you call it?

clipboard.png
Vue.prototype,this.$moment();

main.js


main.jsthis.$moment this.$momentthisthis,


:
clipboard.png

created(){
      console.log(this.$moment());
      this.$moment.locale("zh-cn");
    },
    filters:{
      formatTime(time){
        return this.$moment(time).fromNow();
      },
    },

can be called in the component using this.$moment () , but not in main.js . At this point, this points to window , and you can call


in this way Vue.prototype.$moment () .

introduced in main.js:

clipboard.png

clipboard.png
:

clipboard.png


read the error message, it should be the wrong value of this. See if the arrow function is used in the options ( hook function or data or watch or computed ). There is no specific code can only think of this.

tried, this is not a vue instance in filters . It is recommended that you implement your requirements through the computed attribute.

searched the relevant information: a href= "https://github.com/vuejs/vue/issues/5998" rel=" nofollow noreferrer "> original words :

This is intentional in 2.x. Filters should be pure functions and should not be dependent on this context. If you need this you should use a computed property or just a method costs $translate (foo)

to put it simply, vue2+ deliberately does not give you access to this in filters .


when developing a single-page component, Vue is not a global object, it can only be accessed directly on the main.js. You can hang Vue under window in main.js, as follows:

  

upstairs faymi's answer is correct.
in addition, the owner of the building can also import it on demand in each component and use it directly, for example, in ChildA.vue,
import moment from "moment";
console.log (moment ('2018-04-16'). ToDate ());

Menu