鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ vue注冊了全局方法,調(diào)用的時候獲取不到怎么辦

vue注冊了全局方法,調(diào)用的時候獲取不到怎么辦

clipboard.png
這是打印的Vue.prototype,和this.$moment();

以下是main.js中的代碼

import moment from 'moment';
Object.defineProperty(Vue.prototype, '$moment', { value: moment });
// Vue.prototype.$moment=moment;
console.log(Vue.prototype);
console.log(this.$moment());

根據(jù)樓上大神所說,main.js直接打印this.$moment 跟在組件中this.$moment的this不是一個this,應(yīng)該直接在組件中輸入,我試了下,確實(shí)可以在組件中輸出

console.log(this.$moment());

但是使用相關(guān)的方法依然不生效:
clipboard.png

created(){
      console.log(this.$moment());
      this.$moment.locale('zh-cn');
    },
    filters:{
      formatTime(time){
        return this.$moment(time).fromNow();
      },
    },
回答
編輯回答
瞄小懶
  1. 打印出 this,就在里面找?。?/li>
  2. 找不到?那肯定是沒綁定了;
  3. 想用 this調(diào)用,肯定要綁定到原型鏈上,
  4. 那就去 main.js 綁定,Vue.prototype.moment = moment
  5. 導(dǎo)入組件后this.moment調(diào)用
2018年4月24日 12:27
編輯回答
巷尾

單頁面組件開發(fā)時,Vue 不是一個全局對象,它只在 main.js 上可以直接訪問。可以在 main.js 中把 Vue 掛在window下,如下:

import moment from 'moment';
Object.defineProperty(Vue.prototype, '$moment', { value: moment });
// Vue.prototype.$moment=moment;
console.log(Vue.prototype);
console.log(this.$moment());
window.Vue = Vue;
2018年9月15日 17:28
編輯回答
怪痞

在main.js引入:

clipboard.png

clipboard.png
在組件中引用:

clipboard.png

2017年4月20日 17:02
編輯回答
熟稔

在組件中可以使用 this.$moment() 這種方式調(diào)用,在 main.js中是不行的,這時候this指向window,你可以使用 Vue.prototype.$moment() 這樣的方式調(diào)用

2017年6月27日 13:05
編輯回答
淡墨

樓上 faymi 的回答很對。
除此之外,樓主還可以在每個組件中按需導(dǎo)入,直接使用即可,比如在 ChildA.vue中,
import moment from "moment";
console.log(moment('2018-04-16').toDate());

2017年3月3日 14:34
編輯回答
笑忘初

看了下報錯信息,應(yīng)該是this的取值不對。 看看有沒有在選項(xiàng)中(鉤子函數(shù) or data or watch or computed)用了箭頭函數(shù)。沒有具體的代碼只能想到這個了。

試了一下,在filters中this不是vue實(shí)例。建議通過computed屬性來實(shí)現(xiàn)你的需求。

搜了下相關(guān)信息:尤大原話

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 e.g. $translate(foo)

簡單來說就是vue2+是故意不給你在filters里取到this的~

2017年2月23日 00:21