Vue.js Cookbook: 添加实例属性; 👍 axios(4万➕✨)访问API; filters过滤器;

add instance properties

//加上$,防止和已经定义的data,method, computed的名字重复,导致被覆写。
//可以自定义添加其他符号。

Vue.prototype.$appName = 'Myqq1 App'
var mm = new Vue({ data: { appName: 'xxxxx' }, beforeCreate: function () { console.log(this.$appName) }, created: function() { console.log(this.appName) } })

真实示例: 用axios替换Vue Resource。

注意⚠️: Vue Resource插件已经不再被官方推荐使用。但仍然可用,不过未来不再维护。(原文)

替换:

  1. 可以使用$.ajax
  2. 新用户可以使用Axios。当前最流行的HTTP client library,覆盖了vue-resource。
  3. 如果喜欢使用lower-level,使用标准的 fetch API. 好处是无需额外的加载一个外部资源。但没有被浏览器完全支持,需要使用polyfill。因此使用Axios的更多一些。

使用Vue.prototype.$http = axios。让$http的值是axios, 这样仍旧可以使用传统的写法了。

我的code pen:

https://codepen.io/chentianwei411/pen/rZXavE

原型方法的上下文

javaScript的原型的方法会获得该实例的上下文。就是实例本身this,可以访问实例的数据,computed,method等定义在实例上的东西。



Vue.prototype.$reverseText
= function (propertyName) {
//this指的就是实例本身
//Vue {_uid: 0, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: Vue, …}
this[propertyName] = this[propertyName] .split('') .reverse() .join('') } new Vue({ data: { message: 'Hello' }, created: function () { console.log(this.message) // => "Hello" this.$reverseText('message') console.log(this.message) // => "olleH" } })

但是,原型方法如果使用箭头函数的话,,this绑定的上下文不会正常工作,因为它们会隐式绑定父作用域。所以会出错。

⚠️:我是在Rails中的application.js中定义的Vue原型方法$reverseText。所以这个方法中的this绑定的是父作用域,即文件application.js这个作用域:见下图

Vue.prototype.$reverseText = propertyName => {
 //this是一个{__esModule: true}
 console.log(this);
this[propertyName] = this[propertyName] .split('') .reverse() .join('') }

 


使用 axios 访问 API

git https://github.com/axios/axios

实例:看过滤器一章https://cn.vuejs.org/v2/guide/filters.html

//写在new Vue({...})内部。

filters: { currencydecimal (value) {
return value.toFixed(2) } },

一个简单的axios使用:

axios
  .get('https://api.coindesk.com/v1/bpi/currentprice.json')
  .then(response => (this.info = response.data.bpi))
  .catch(error => console.log(error))

.finally(() => this.loading = false

真实案例: my code pen:

https://codepen.io/chentianwei411/pen/OoKVNo

重点:

1. Filters过滤器:

当在HTML中遇到, {{ currency.rate_float | currencydecimal }} 会调用过滤器中的方法currencydecimal,参数是currency.rote_float, 返回的结果显示在 {{ 内 }}

过滤器使用地点:

除了{{ xx }}内,还有用在v-bind表达式内部。

{{ message | capitalize }}

<div v-bind:id="rawId | formatId"></div>

定义位置:

1. 在new Vue()内使用 filters: {  xxx }

2.在初始化实例前面,使用Vue.filter("名字", function(value) {  xxx  })

Fetch

还可以使用Fetch API 这是原生API,省资源。但是还有浏览器不支持。需要polyfill。

如果你对使用 Fetch API 有兴趣,这里有一些非常棒的文章来解释如何使用它。

原文地址:https://www.cnblogs.com/chentianwei/p/9705909.html