1. 程式人生 > >Vue框架引入JS庫的正確姿勢

Vue框架引入JS庫的正確姿勢

eat nat microsoft creat time ros size .com target

參考自:https://mp.weixin.qq.com/s?src=3&timestamp=1527154113&ver=1&signature=tWGeTa86gyK*RL0P7nwlA6-8V14FjzxUTh7CM9kQLjnXjchkqgw6Lm3C5JXI-ba9wmXjXglUMApGCHe2aIvGC-eWC8KuNsUl0PLTWLjdbjhiVZDS9SGRQuOc-pe0achyII43bi*cyMkSHrrC2Vb8d0Q0OW7DrF-RZ202wJqKED4=

正確引入方式

最簡單靠譜的方式是用庫變成Vue的原型對象的屬性。

import moment from ‘moment‘;
Object.definePrototype(Vue.prototype, 
‘$moment‘, { value: moment });

也可以:

Vue.prototype.$moment = moment;

由於所有的組件都會繼承Vue原型對象上的方法,因此這些方法在任何組件文件中都能通過this.$moment 訪問到:

export default {
  created() {
    console.log(‘The time is ‘ . this.$moment().format("HH:mm"));
  }
}

Vue框架引入JS庫的正確姿勢