为什么要捐赠
API 资源管理器
其他工具

提示

有关 UMD 构建的使用方法,请参见 此处

openURL

import { openURL } from 'quasar'

openURL('http://...')

// full syntax:
openURL(
  String url,
  Function rejectFn, // optional; gets called if window cannot be opened
  Object windowFeatures // optional requested features for the new window
)

它将处理在 Cordova、Electron 或浏览器下运行时涉及的怪癖,包括通知用户他/她必须确认打开弹出窗口。

在使用 Cordova(或 Capacitor)包装时,最好(但不是“必须”)也安装 InAppBrowser Cordova 插件,以便 openURL 可以挂钩到该插件。

如果在 iOS 上运行并且安装了 cordova-plugin-safariviewcontroller,那么 openURL 将首先尝试挂钩到它。

可选的 windowFeatures 参数应该是一个对象,包含来自 window.open() windowFeatures 的键以及布尔值(如以下示例所示)。请注意,当 openURL 不使用 window.open() 时,这些功能将不会被考虑。

openURL() 使用 windowFeatures 的示例

openURL(
  'http://...',
  undefined, // in this example we don't care about the rejectFn()

  // this is the windowFeatures Object param:
  {
    noopener: true, // this is set by default for security purposes
                    // but it can be disabled if specified with a Boolean false value
    menubar: true,
    toolbar: true,
    noreferrer: true,
    // .....any other window features
  }
)

提示

如果您想在 Cordova 应用程序中打开电话拨号器,请不要使用 openURL()。相反,您应该直接使用 <a href="tel:123456789"> 标签或 <QBtn href="tel:123456789">

copyToClipboard

以下是一个将一些文本复制到剪贴板的辅助函数。该方法返回一个 Promise。

import { copyToClipboard } from 'quasar'

copyToClipboard('some text')
  .then(() => {
    // success!
  })
  .catch(() => {
    // fail
  })

exportFile

以下是一个触发浏览器开始下载具有指定内容的文件的辅助函数。

/**
 * Forces browser to download file with specified content
 *
 * @param {*} fileName - String
 * @param {*} rawData - String | ArrayBuffer | ArrayBufferView | Blob
 * @param {*} opts - String (mimeType) or Object
 *                   Object form: { mimeType?: String, byteOrderMark?: String | Uint8Array, encoding?: String }
 * @returns Boolean | Error
 */

可选的 opts 参数可以是字符串(mimeType)或具有以下格式的对象

示例

import { exportFile } from 'quasar'

const status = exportFile('important.txt', 'some content')

if (status === true) {
  // browser allowed it
}
else {
  // browser denied it
  console.log('Error: ' + status)
}
import { exportFile } from 'quasar'

const status = exportFile('file.csv', 'éà; ça; 12\nà@€; çï; 13', {
  encoding: 'windows-1252',
  mimeType: 'text/csv;charset=windows-1252;'
})

if (status === true) {
  // browser allowed it
}
else {
  // browser denied it
  console.error('Error: ' + status)
}

runSequentialPromises
v2.8.4+

以下是一个按顺序运行多个 Promise 的辅助函数。可选地在多个线程上。

/**
 * Run a list of Promises sequentially, optionally on multiple threads.
 *
 * @param {*} sequentialPromises - Array of Functions or Object with Functions as values
 *                          Array of Function form: [ (resultAggregator: Array) => Promise<any>, ... ]
 *                          Object form: { [key: string]: (resultAggregator: object) => Promise<any>, ... }
 * @param {*} opts - Optional options Object
 *                   Object form: { threadsNumber?: number, abortOnFail?: boolean }
 *                   Default: { threadsNumber: 1, abortOnFail: true }
 *                   When configuring threadsNumber AND using http requests, be
 *                       aware of the maximum threads that the hosting browser
 *                       supports (usually 5); any number of threads above that
 *                       won't add any real benefits
 * @returns Promise<Array<Object> | Object>
 *    With opts.abortOnFail set to true (which is default):
 *        When sequentialPromises param is Array:
 *          The Promise resolves with an Array of Objects of the following form:
 *             [ { key: number, status: 'fulfilled', value: any }, ... ]
 *          The Promise rejects with an Object of the following form:
 *             { key: number, status: 'rejected', reason: Error, resultAggregator: array }
 *        When sequentialPromises param is Object:
 *          The Promise resolves with an Object of the following form:
 *             { [key: string]: { key: string, status: 'fulfilled', value: any }, ... }
 *          The Promise rejects with an Object of the following form:
 *             { key: string, status: 'rejected', reason: Error, resultAggregator: object }
 *    With opts.abortOnFail set to false:
 *       The Promise is never rejected (no catch() needed)
 *       The Promise resolves with:
 *          An Array of Objects (when sequentialPromises param is also an Array) of the following form:
 *             [ { key: number, status: 'fulfilled', value: any } | { status: 'rejected', reason: Error }, ... ]
 *          An Object (when sequentialPromises param is also an Object) of the following form:
 *             { [key: string]: { key: string, status: 'fulfilled', value: any } | { key: string, status: 'rejected', reason: Error }, ... }
 */

请注意

  • sequentialPromises 参数是一个函数数组(每个函数返回一个 Promise)
  • sequentialPromises 中的每个函数都接收一个参数,即 resultAggregator,因此基本上您可以使用先前 Promise 的结果来决定如何处理当前 Promise;resultAggregator 中尚未解决的每个条目都被标记为 null
  • opts 参数是可选的。

通用示例(sequentialPromises 参数为数组)

import { runSequentialPromises } from 'quasar'

runSequentialPromises([
  (resultAggregator) => new Promise((resolve, reject) => { /* do some work... */ }),
  (resultAggregator) => new Promise((resolve, reject) => { /* do some work... */ })
  // ...
]).then(resultAggregator => {
  // resultAggregator is ordered in the same way as the promises above
  console.log('result from first Promise:', resultAggregator[0].value)
  console.log('result from second Promise:', resultAggregator[1].value)
  // ...
}).catch(errResult => {
  console.error(`Error encountered on job #${ errResult.key }:`)
  console.error(errResult.reason)
  console.log('Managed to get these results before this error:')
  console.log(errResult.resultAggregator)
})

通用示例(sequentialPromises 参数为对象)

import { runSequentialPromises } from 'quasar'

runSequentialPromises({
  phones: (resultAggregator) => new Promise((resolve, reject) => { /* do some work... */ }),
  laptops: (resultAggregator) => new Promise((resolve, reject) => { /* do some work... */ })
  // ...
}).then(resultAggregator => {
  console.log('result from first Promise:', resultAggregator.phones.value)
  console.log('result from second Promise:', resultAggregator.laptops.value)
  // ...
}).catch(errResult => {
  console.error(`Error encountered on job (${ errResult.key}):`)
  console.error(errResult.reason)
  console.log('Managed to get these results before this error:')
  console.log(errResult.resultAggregator)
})

使用先前结果的示例

import { runSequentialPromises } from 'quasar'

runSequentialPromises({
  phones: () => new Promise((resolve, reject) => { /* do some work... */ }),
  vendors: (resultAggregator) => {
    new Promise((resolve, reject) => {
      // You can do something with resultAggregator.phones.value here...
      // Since are using the default abortOnFail option, the result is guaranteed to exist,
      // so you don't have to guard resultAggregator.phones against "null"
    })
  }
  // ...
})

使用 Axios 的示例

import { runSequentialPromises } from 'quasar'
import axios from 'axios'

const keyList = [ 'users', 'phones', 'laptops' ]

runSequentialPromises([
  () => axios.get('https://some-url.com/users'),
  () => axios.get('https://some-other-url.com/items/phones'),
  () => axios.get('https://some-other-url.com/items/laptops')
]).then(resultAggregator => {
  // resultAggregator is ordered in the same way as the promises above
  resultAggregator.forEach(result => {
    console.log(keyList[ result.key ], result.value) // example: users {...}
  })
}).catch(errResult => {
  console.error(`Error encountered while fetching ${ keyList[ errResult.key ] }:`)
  console.error(errResult.reason)
  console.log('Managed to get these results before this error:')
  console.log(errResult.resultAggregator)
})

// **equivalent** example with sequentialPromises as Object:

runSequentialPromises({
  users: () => axios.get('https://some-url.com/users'),
  phones: () => axios.get('https://some-other-url.com/items/phones'),
  laptops: () => axios.get('https://some-other-url.com/items/laptops')
}).then(resultAggregator => {
  console.log('users:', resultAggregator.users.value)
  console.log('phones:', resultAggregator.phones.value)
  console.log('laptops:', resultAggregator.laptops.value)
}).catch(errResult => {
  console.error(`Error encountered while fetching ${ errResult.key }:`)
  console.error(errResult.reason)
  console.log('Managed to get these results before this error:')
  console.log(errResult.resultAggregator)
})

将 abortOnFail 设置为 false 的示例

import { runSequentialPromises } from 'quasar'
import axios from 'axios'

// notice no "catch()"; runSequentialPromises() will always resolve
runSequentialPromises(
  {
    users: () => axios.get('https://some-url.com/users'),
    phones: () => axios.get('https://some-other-url.com/items/phones'),
    laptops: () => axios.get('https://some-other-url.com/items/laptops')
  },
  { abortOnFail: false }
).then(resultAggregator => {
  Object.values(resultAggregator).forEach(result => {
    if (result.status === 'rejected') {
      console.log(`Failed to fetch ${ result.key }:`, result.reason)
    }
    else {
      console.log(`Succeeded to fetch ${ result.key }:`, result.value)
    }
  })
})

在配置 threadsNumber(opts > threadsNumber)并使用 http 请求时,请注意托管浏览器支持的最大线程数(通常为 5)。任何超过该数量的线程都不会带来任何实际好处。

import { runSequentialPromises } from 'quasar'

runSequentialPromises([ /* ... */ ], { threadsNumber: 3 })
  .then(resultAggregator => {
    resultAggregator.forEach(result => {
      console.log(result.value)
    })
  })
  .catch(errResult => {
    console.error(`Error encountered:`)
    console.error(errResult.reason)
    console.log('Managed to get these results before this error:')
    console.log(errResult.resultAggregator)
  })

debounce

如果您的应用程序使用 JavaScript 来完成繁重的任务,则去抖动函数对于确保给定任务不会频繁触发以至于导致浏览器性能下降至关重要。去抖动函数会限制函数触发的速率。

去抖动会强制函数在一定时间内未被调用之前不会再次被调用。例如,“仅在 100 毫秒内未调用该函数时才执行该函数”。

一个简单的例子:您在窗口上有一个调整大小监听器,它会执行一些元素尺寸计算(可能还会重新定位一些元素)。这本身并不是一项繁重的任务,但如果在多次调整大小后重复触发,它会真正降低您的应用程序速度。所以为什么不限制函数触发的速率呢?

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
import { debounce } from 'quasar'

(Debounced Function) debounce(Function fn, Number milliseconds_to_wait, Boolean immediate)

// Example:
window.addEventListener(
  'resize',
  debounce(function() {
    // .... things to do ...
  }, 300 /*ms to wait*/)
)

或在 .vue 文件中作为方法调用

methods: {
  myMethod () { .... }
},

created () {
  this.myMethod = debounce(this.myMethod, 500)
}

警告

使用类似 myMethod: debounce(function () { // Code }, 500) 的方法声明来去抖动您的函数意味着去抖动的方法将在该组件的所有渲染实例之间共享,因此去抖动也是共享的。此外,this.myMethod.cancel() 不会起作用,因为 Vue 会将每个方法包装在另一个函数中以确保正确的 this 绑定。应避免通过遵循上面的代码片段来进行此操作。

还有一个 frameDebounce 可用,它会在下一个浏览器帧被安排运行之前延迟调用您的函数(阅读有关 requestAnimationFrame 的内容)。

import { frameDebounce } from 'quasar'

(Debounced Function) frameDebounce(Function fn)

// Example:
window.addEventListener(
  'resize',
  frameDebounce(function() {
    .... things to do ...
  })
)

throttle

节流会强制函数在一段时间内最多可以被调用的次数。例如,“每 X 毫秒最多执行一次该函数”。

import { throttle } from 'quasar'

(Throttled Function) throttle(Function fn, Number limit_in_milliseconds)

// Example:
window.addEventListener(
  'resize',
  throttle(function() {
    .... things to do ...
  }, 300 /* execute at most once every 0.3s */)
)

或在 .vue 文件中作为方法调用

methods: {
  myMethod () { .... }
},

created () {
  this.myMethod = throttle(this.myMethod, 500)
}

警告

使用类似 myMethod: throttle(function () { // Code }, 500) 的方法声明来节流您的函数意味着节流的方法将在该组件的所有渲染实例之间共享,因此节流也是共享的。应避免通过遵循上面的代码片段来进行此操作。

extend - (深度)复制对象

jQuery.extend() 的基本重生。接受相同的参数

import { extend } from 'quasar'

let newObject = extend([Boolean deepCopy], targetObj, obj, ...)

注意对象中的方法。

uid - 生成 UID

生成唯一的标识符

import { uid } from 'quasar'

let uid = uid()
// Example: 501e7ae1-7e6f-b923-3e84-4e946bff31a8

testPattern

针对特定模式进行测试。

import { patterns } from 'quasar'

const { testPattern } = patterns

testPattern.email('[email protected]') // true
testPattern.email('foo') // false

testPattern.hexColor('#fff') // true
testPattern.hexColor('#ffffff') // true
testPattern.hexColor('#FFF') // true
testPattern.hexColor('#gggggg') // false

查看完整的模式列表 这里.