API 浏览器
如何使用 Vue

在开始使用 Quasar 之前,最好先熟悉 ES6 并对 Vue 3 的工作原理有相当好的了解。(ES6 快速概览ES6 完整功能列表 - 不用担心,你不需要了解所有 ES6 内容)。对于熟悉响应式 UI 的开发者,Vue 3 文档 本身最多只需半天时间即可从头到尾阅读,它将帮助你了解如何使用和配置 Quasar 组件。

¥Before you begin with Quasar, it is a good idea to get acquainted with ES6 and have a fairly good knowledge about how Vue 3 works. (Quick overview of ES6 and ES6 complete list of features – don’t worry, you don’t need to understand ALL of ES6). For devs experienced with reactive UIs, the Vue 3 documentation itself takes a half-day at most to read top-to-bottom and will help you understand how Quasar components can be used and configured.

提示

如果你是 Vue 和响应式 UI 库的初学者,并且想要一个好的教程,我们建议你看一下 Vue 和 Quasar 视频教程

¥If you are a total beginner to Vue and reactive UI libraries and want a good tutorial, we recommend you take a look at Vue and Quasar video tutorials.

阅读 Vue 文档后,让我们来解答一些最常见的问题,例如 “如何使用 Quasar 组件、Vue 属性、方法和事件”。

¥After reading the Vue documentation, let’s clear up some of the most frequently asked questions, like “How can I use Quasar components, Vue properties, methods and events”.

Vue 单文件组件 (SFC)(Vue Single File Components (SFC))

¥Vue Single File Components (SFC)

你将使用包含多个部分的 *.vue 文件构建你的 Quasar 应用:template (HTML)、script (Javascript) 和 style (CSS/SASS/SCSS/Stylus/Less) 均位于同一文件中。

¥You’ll be building your Quasar app using *.vue files which contain multiple sections: template (HTML), script (Javascript) and style (CSS/SASS/SCSS/Stylus/Less) all in the same file.

目前建议使用 Composition API 和 <script setup>。查看 Vue.js 文档 了解更多信息。

¥Currently, it is recommended to use Composition API with <script setup>. Check out Vue.js documentation for more information.

<template>
  <!-- you define your Vue template here -->
</template>

<script setup>
// This is where your Javascript goes
// to define your Vue component, which
// can be a Layout, a Page or your own
// component used throughout the app.
</script>

<style>
/* This is where your CSS goes */
</style>

但是如果你愿意,仍然可以使用 Composition API,而无需 <script setup> 或 Options API。唯一的区别在于 <script> 标签。

¥But you can still use Composition API without <script setup> or Options API if you wish. The only difference is within the <script> tag.

<template>
  <!-- you define your Vue template here -->
</template>

<script>
// This is where your Javascript goes
// to define your Vue component, which
// can be a Layout, a Page or your own
// component used throughout the app.

export default {
  //
}
</script>

<style>
/* This is where your CSS goes */
</style>

CSS 预处理器(CSS preprocessors)

¥CSS preprocessors

对于 <style> 标签,你也可以使用任何你想要的 CSS 预处理器。Sass/SCSS(推荐)开箱即用。

¥For the <style> tag, you can also use whatever CSS preprocessor you want. Sass/SCSS (recommended) is available out of the box.

你可以指定你希望你选择的预处理器来处理你正在编写的 CSS 代码:

¥You can specify you want your chosen preprocessor to handle the CSS code that you’re writing:

<!-- notice lang="sass" -->
<style lang="sass">
.some-div
  font-size: 15px
</style>

<!-- notice lang="scss" -->
<style lang="scss">
.some-div {
  font-size: 15px;
}
</style>

使用 Quasar 指令(Using Quasar Directives)

¥Using Quasar Directives

Quasar 附带一些自定义 Vue 指令。这些指令几乎可以应用于任何 DOM 元素或组件。

¥Quasar comes with a few custom Vue Directives. These directives can be applied on almost any DOM element or Component.

Quasar 指令示例:

¥Example of a Quasar directive:

<div v-ripple>Click Me</div>

请注意,Ripple 在 HTML 模板中是如何用作 v-ripple 的。Vue 指令以 v- 为前缀。

¥Notice how Ripple is used in the HTML template as v-ripple. Vue directives are prefixed with v-.

<div v-touch-pan="handler">...</div>
<div v-touch-swipe="handler">...</div>
<div v-ripple>Click me. I got ripples.</div>

使用 Quasar 组件(Using Quasar Components)

¥Using Quasar Components

Quasar 组件的名称以 “Q” 开头,例如 “QBtn” 或 “QElementResizeObserver”。为了使用它们,你需要在 /quasar.config 文件中添加对它们的引用。

¥Quasar components have names beginning with “Q” like “QBtn” or “QElementResizeObserver”. In order to use them, you need to add a reference to them in the /quasar.config file.

让我们以 QBtn 和 QIcon 为例,了解如何将这些组件嵌入到我们的应用中:

¥Let’s take the following example with a QBtn and QIcon and then we’ll see how to embed these components in our app:

<div>
  <q-btn @click="doSomething" label="Do something" />
  <q-icon name="alarm" />
</div>

请注意,QBtn 在 Vue HTML 模板中是如何用作 <q-btn> 的。如果我们在模板中将其用作 <q-element-resize-observer> 属性。

¥Notice how QBtn is used in the Vue HTML template as <q-btn>. If we’d import QElementResizeObserver, then we’d use it in template as <q-element-resize-observer>.

使用 Quasar 插件(Using Quasar Plugins)

¥Using Quasar Plugins

Quasar 插件是你可以在 Vue 文件内部以及外部使用的功能,例如 Notify、BottomSheet、AppVisibility 等。

¥Quasar Plugins are features that you can use both in your Vue files as well as outside of them, like Notify, BottomSheet, AppVisibility and so on.

警告

在你的应用中使用它们之前,你需要在 /quasar.config 文件中添加对它们的引用(如下所示)。

¥Before using them in your app, you need to add a reference to them in the /quasar.config file (as shown below).

framework: {
  plugins: [ 'Notify', 'BottomSheet' ]
}

让我们以 Notify 为例,看看如何使用它。在 Vue 文件中,你可以编写类似以下内容(Composition API):

¥Let’s take Notify as an example and see how we can then use it. In a Vue file, you’d write something like this (Composition API):

<template>
  <div>
    <q-btn
      @click="$q.notify('My message')"
      color="primary"
      label="Show a notification"
    />

    <q-btn
      @click="showNotification"
      color="primary"
      label="Show another notification"
    />
  </div>
</template>

<script>
import { useQuasar } from 'quasar'

export default {
  setup () {
    const $q = useQuasar()

    function showNotification () {
      $q.notify('Some other message')
    }

    return {
      showNotification
    }
  }
}
</script>

请注意,在模板区域中,我们使用的是 $q.<plugin-name>

¥Notice that in the template area we’re using $q.<plugin-name>.

Options API 中等效的脚本部分:

¥An equivalent script section in Options API:

export default {
  methods: {
    showNotification () {
      this.$q.notify('Some other message')
    }
  }
}

现在让我们看一个在 Vue 文件之外使用 Notify 的示例:

¥Now let’s see an example of Notify being used outside of a Vue file:

import { Notify } from 'quasar'

// ...
Notify.create('My message')

自闭合标签(Self-Closing Tags)

¥Self-Closing Tags

危险

使用 Quasar UMD 版本时,请勿使用自闭合标签形式。你的浏览器在 Vue 解析你的 DOM 元素之前会解析 HTML,因此你的 HTML 语法必须正确。未知标签(例如 Vue 组件)无法自动关闭,因为你的浏览器会将它们解释为你打开了一个标签但从未关闭它。

¥Do NOT use self-closing tag form when you are using Quasar UMD version. Your browser is interpreting the HTML before Vue parses your DOM elements, so your HTML syntax must be correct. Unknown tags (like Vue components) cannot be self-closing because your browser will interpret those as if you are opening a tag but never closing it.

某些 Quasar 组件不需要你在其中包含 HTML 内容。在这种情况下,你可以将它们用作自闭合标签。下面是一个使用 QIcon 的示例:

¥Some Quasar components do not need you to include HTML content inside of them. In this case, you can use them as self-closing tags. One example with QIcon below:

<q-icon name="cloud" />

自闭合意味着上述模板相当于:

¥Self-closing means the above template is the equivalent to:

<q-icon name="cloud"></q-icon>

两种形式均有效且可以使用,但 UMD 除外,因为 UMD 必须明确关闭标签。它对常规 DOM 元素的作用相同:

¥Both forms are valid and can be used, except for UMD where you must explicitly close the tags. It works the same with regular DOM elements:

<div class="col" />
<!-- equivalent to: -->
<div class="col"></div>

某些 eslint-plugin-vue linting 规则实际上强制使用自闭合语法。

¥Some eslint-plugin-vue linting rules actually enforce using the self-closing syntax.

处理 Vue 属性(Handling Vue Properties)

¥Handling Vue Properties

让我们使用一个支持以下属性的伪 Quasar 组件(我们称之为 QBogus)来举几个例子。我们将在以下章节中讨论每种 Vue 属性。

¥Let’s take some examples with a bogus Quasar component (we will call it QBogus) that supports the properties below. We will discuss each of the types of Vue properties in the below sections.

Vue 属性类型描述
infinite布尔值无限幻灯片滚动
size字符串加载栏的粗细。
speed数字加载栏应该以多快的速度更新其值(以毫秒为单位)。
columns对象定义列的对象(参见下面的 “列定义”)。
offset数组包含两个数字的数组。水平和垂直偏移量(以像素为单位)。

布尔属性(Boolean Property)

¥Boolean Property

布尔属性表示它只接受严格的布尔值。这些值不会转换为布尔值,因此你必须确保使用的是真正的布尔值。

¥A boolean property means it only accepts a strictly Boolean value. The values will not be cast to Boolean, so you must ensure you are using a true Boolean.

提示

在 Quasar 中,所有布尔属性的默认值都是 false。因此,你不必明确地为它们分配 false 值。

¥In Quasar, all Boolean properties have false as the default value. As a result, you don’t have to explictly assign them the false value.

如果你尝试控制该属性并在运行时动态更改它,请将其绑定到你作用域中的变量:

¥If you are trying to control that property and change it dynamically at runtime, then bind it to a variable in your scope:

<template>
  <q-bogus :infinite="myInfiniteVariable" />
</template>

<script>
import { ref } from 'vue'

export default {
  setup () {
    const myInfiniteVariable = ref(false)
    return {
      myInfiniteVariable
    }
  }
}
</script>

另一方面,如果你知道这个布尔值不会改变,你可以使用变量的简写版本,例如组件属性,只需指定它即可。换句话说,如果你不将变量绑定到组件作用域中的变量,因为它始终是 true

¥If, on the other hand, you know this Boolean value is not going to change, you can use the shorthand version of the variable like a component attribute and just specify it. In other words, if you don’t bind the variable to a variable in the component’s scope as it will always be true:

<template>
  <q-bogus infinite />

  <!--
    the following is perfectly valid,
    but it's a longer version
  -->
  <q-bogus :infinite="true" />
</template>

字符串属性(String Property)

¥String Property

可以想象,此类属性的值必须为字符串。

¥As you can imagine, Strings are required as a value for this type of property.

<template>
  <!--
    direct assignment, no need for
    a variable in our scope
  -->
  <q-bogus size="24px" />

  <!--
    we can also bind it to a variable
    in our scope so we can dynamically
    change it
  -->
  <q-bogus :size="mySize" />
</template>

<script>
import { ref } from 'vue'

export default {
  setup () {
    // notice String as value
    const mySize = ref('16px')
    return {
      mySize
    }
  }
}
</script>

数字属性(Number Property)

¥Number Property

<template>
  <!--
    Case 1. Direct assignment.
    Notice the colon (":") before property name.
  -->
  <q-bogus :speed="50" />

  <!-- Case 2. Assignment through a scope variable -->
  <q-bogus :speed="myNumber" />
</template>

<script>
import { ref } from 'vue'

export default {
  setup () {
    // notice Number as value
    const myNumber = ref(50)
    return {
      myNumber
    }
  }
}
</script>

对象属性(Object Property)

¥Object Property

<template>
  <!-- Case 1. Direct assignment. -->
  <q-bogus :columns="{key: 'value', anotherKey: 'another value'}" />

  <!-- Case 2. Assignment through a scope variable -->
  <q-bogus :columns="myColumns" />
</template>

<script>
import { ref } from 'vue'

export default {
  setup () {
    const myColumns = ref({
      key: 'value',
      anotherKey: 'another value'
    })

    return { myColumns }
  }
}
</script>

数组属性(Array Property)

¥Array Property

<template>
  <!-- Case 1. Direct assignment. -->
  <q-bogus :offset="[10, 20]" />

  <!-- Case 2. Assignment through a scope variable -->
  <q-bogus :offset="myOffset" />
</template>

<script>
export default {
  setup () {
    return {
      myOffset: [10, 20]
    }
  }
}
</script>

处理 Vue 方法(Handling Vue Methods)

¥Handling Vue Methods

你会注意到,在整个文档中,某些 Quasar 组件具有可调用的方法。示例:

¥You will notice throughout the documentation that some Quasar components have methods that can be called. Example:

Vue 方法描述
next()转到下一张幻灯片。
previous(doneFn)转到上一张幻灯片。
toggleFullscreen()切换全屏模式。

为了访问这些方法,你需要先在组件上设置 Vue 引用。以下是 Composition API 的示例:

¥In order for you to access these methods, you will need to set a Vue reference on the component first. Here’s an example with Composition API:

<template>
  <!--
    Notice ref="myRef". We will use the name
    assigned to "ref" in the script part below
  -->
  <q-bogus ref="myRef" />
</template>

<script>
import { ref, onMounted } from 'vue'

export default {
  setup () {
    const myRef = ref(null)

    // after the component has mounted into DOM:
    onMounted(() => {
      // we call "next()" method of our component
      myRef.value.next()
    })
    // calling before mount point might result in errors
    // as Vue hasn't yet prepared the Vue reference

    // we expose myRef to the scope so Vue
    // can use it in the template as well
    return { myRef }
  }
}
</script>

以下是相同示例,但使用了选项 API:

¥And here is the same example, but with Options API:

<template>
  <!--
    Notice ref="myRef". We will use the name
    assigned to "ref" in the script part below
  -->
  <q-bogus ref="myRef" />
</template>

<script>
export default {
  // we can now access `this.$refs.myRef`
  // an example on the mounted() Vue component hook
  mounted () {
    // calling "next()" method:
    this.$refs.myRef.next()
  }
  // calling before mount point might result in errors
  // as Vue hasn't yet prepared the Vue reference
}
</script>

处理 Vue 事件(Handling Vue Events)

¥Handling Vue Events

你会注意到,在整个文档中,某些 Quasar 组件包含一个名为 “Vue 事件” 的部分。

¥You will notice throughout the documentation that some Quasar components have a section called “Vue Events”.

“Vue 事件” 示例:

¥Example of “Vue Events”:

事件名称描述
@show在 Modal 显示后立即触发。
@hide在 Modal 隐藏后立即触发。

为了在触发这些事件时捕获它们,你需要添加监听器将它们添加到 HTML 模板中的组件本身。以下是示例:

¥In order for you to catch these events, when they are triggered, you will need to add listeners for them on the component itself in the HTML template. Here’s an example:

<template>
  <q-bogus @show="doSomething" @hide="doSomethingElse" />
</template>

<script>
export default {
  setup () {
    function doSomething () {
      // this method has been called (in this case)
      // because @show event was triggered by QBogus component
    }

    function doSomethingElse () {
      // this method has been called (in this case)
      // because @hide event was triggered by QBogus component
    }

    return {
      doSomething,
      doSomethingElse
    }
  }
}
</script>