Vue Template Script Style

Posted on  by admin

There are numerous ways to define templates in Vue, but many of them don't work so well in production.

The docs even recommend avoiding some of them. Here's 3 ways to define templates for Vue components that work well with server-side rendering:. You can define a template in vanilla JavaScript as a string literal or template literal. This approach means a component's HTML and JavaScript stay in the same file, which is generally considered a positive.

The downside is that you don't get HTML syntax highlighting. You can use this approach but use a function to load the string. This splits HTML and JavaScript into separate files to get better syntax highlighting and separation of concerns. Another approach that is similar to string templates is inline templates.

Instead of defining an HTML template for every component, you define all your component HTML in one top-level template. This is similar to slots. The advantage of this approach is you can define all your app's HTML in one template, but still break up business logic into separate components.

Single file components give you the best of both worlds between putting your HTML template in a separate file and putting your HTML template as a string literal.

Directives

Set up your Vue project

Like string literals, everything about a component is in one place. Like separate HTML files, you can get decent syntax highlighting. The tradeoff is that single file components are typically declared in a separate .vue file with its own special syntax.

Use the scoped attribute to style in Vue

Below is an example of .vue syntax. Depending on your IDE, you may need to install an additional package for .vue file syntax highlighting. So in order to compile your component, you need a build step.

VSCode上にLint結果を表示するまで

There are numerous tools that can do this for you, like the Vueify transform for Browserify and vue-loader for Webpack. Under the hood, both of these tools use vue-template-compiler. Here's an example of using vue-template-compiler directly to compile Vue syntax into a component:. Vue School has some of our favorite Vue video courses.

  1. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase.
  2. You’re browsing the documentation for v2.x and earlier. For v3.x, click here.
  3. Vue.js uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying Vue instance’s data.

Shorthands

All Vue.js templates are valid HTML that can be parsed by spec-compliant browsers and HTML parsers. Under the hood, Vue compiles the templates into Virtual DOM render functions. Combined with the reactivity system, Vue is able to intelligently figure out the minimal number of components to re-render and apply the minimal amount of DOM manipulations when the app state changes.

Experience your Vue apps exactly how a user does

コマンドラインでLintするまで

If you are familiar with Virtual DOM concepts and prefer the raw power of JavaScript, you can also directly write render functions instead of templates, with optional JSX support. The most basic form of data binding is text interpolation using the “Mustache” syntax (double curly braces):.

The mustache tag will be replaced with the value of the msg property on the corresponding data object.

npm script作成

Use inline styling

It will also be updated whenever the data object’s msg property changes.

You can also perform one-time interpolations that do not update on data change by using the v-once directive, but keep in mind this will also affect any other bindings on the same node:.

Using JavaScript Expressions

The double mustaches interprets the data as plain text, not HTML. In order to output real HTML, you will need to use the v-html directive:. Using mustaches: {{ rawHtml }}.

Using v-html directive: . The contents of the span will be replaced with the value of the rawHtml property, interpreted as plain HTML - data bindings are ignored. Note that you cannot use v-html to compose template partials, because Vue is not a string-based templating engine. Instead, components are preferred as the fundamental unit for UI reuse and composition.

Dynamically rendering arbitrary HTML on your website can be very dangerous because it can easily lead to XSS vulnerabilities. Only use HTML interpolation on trusted content and never on user-provided content.

Raw HTML

String Templates

Mustaches cannot be used inside HTML attributes.

Instead, use a v-bind directive:. In the case of boolean attributes, where their mere existence implies true, v-bind works a little differently.

自動修正

In this example:. If isButtonDisabled has the value of null, undefined, or false, the disabled attribute will not even be included in the rendered

Object syntax

Update

Template expressions are sandboxed and only have access to a whitelist of globals such as Math and Date.

You should not attempt to access user-defined globals in template expressions. Directives are special attributes with the v- prefix. Directive attribute values are expected to be a single JavaScript expression (with the exception of v-for, which will be discussed later).

Attributes

A directive’s job is to reactively apply side effects to the DOM when the value of its expression changes.

Let’s review the example we saw in the introduction:. Here, the v-if directive would remove/insert the

element based on the truthiness of the value of the expression seen.

Some directives can take an “argument”, denoted by a colon after the directive name. For example, the v-bind directive is used to reactively update an HTML attribute:. Here href is the argument, which tells the v-bind directive to bind the element’s href attribute to the value of the expression url. Another example is the v-on directive, which listens to DOM events:.

Here the argument is the event name to listen to. We will talk about event handling in more detail too. Starting in version 2.6.0, it is also possible to use a JavaScript expression in a directive argument by wrapping it with square brackets:.

v-bind Shorthand

Interpolations

Here attributeName will be dynamically evaluated as a JavaScript expression, and its evaluated value will be used as the final value for the argument.

For example, if your Vue instance has a data property, attributeName, whose value is "href", then this binding will be equivalent to v-bind:href.

  • Similarly, you can use dynamic arguments to bind a handler to a dynamic event name:. In this example, when eventName‘s value is "focus", v-on:[eventName] will be equivalent to v-on:focus. Dynamic arguments are expected to evaluate to a string, with the exception of null.

  • The special value null can be used to explicitly remove the binding. Any other non-string value will trigger a warning. Dynamic argument expressions have some syntax constraints because certain characters, such as spaces and quotes, are invalid inside HTML attribute names.

Arguments

For example, the following is invalid:. The workaround is to either use expressions without spaces or quotes, or replace the complex expression with a computed property.

When using in-DOM templates (i.e., templates written directly in an HTML file), you should also avoid naming keys with uppercase characters, as browsers will coerce attribute names into lowercase:.

Modifiers are special postfixes denoted by a dot, which indicate that a directive should be bound in some special way. For example, the .prevent modifier tells the v-on directive to call event.preventDefault() on the triggered event:.

You’ll see other examples of modifiers later, for v-on and for v-model, when we explore those features.

The v- prefix serves as a visual cue for identifying Vue-specific attributes in your templates.

  • This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives.
  • At the same time, the need for the v- prefix becomes less important when you are building a SPA, where Vue manages every template.
  • Therefore, Vue provides special shorthands for two of the most often used directives, v-bind and v-on:.

They may look a bit different from normal HTML, but : and @ are valid characters for attribute names and all Vue-supported browsers can parse it correctly.

In addition, they do not appear in the final rendered markup.

The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later. ← The Vue InstanceComputed Properties and Watchers →. Caught a mistake or want to contribute to the documentation?Edit this on GitHub!Deployed onNetlify .

Modifiers

More Vue Tutorials

Modified5 years, 4 months ago. I'm creating a large scale application with amazing Vue and Webpack.I don't want to have .vue files since I want to separate them to something like comp.js, comp.pug and comp.styl.

my comp.js will be:. my com.pug will be:. And finally my comp.styl will be:. In first glance everything seems fine till I try using VueRouter and of course elements like or !

Since I wont have any .vue file, I'd assume having alias: { 'vue$': 'vue/dist/vue.common.js' } in Webpack wont help me!

How can I overcome this issue? BTW, that the error I get in the console is:. [Vue warn]: You are using the runtime-only build of Vue where the template option is not available.

Dynamic Arguments

Either pre-compile the templates into render functions, or use the compiler-included build. Worth to mention that I have two entry files:One for whole application. And one for components (sub components are as above):.

And here is my route.js:. So when I have alias: { 'vue$': 'vue/dist/vue.common.js' } added to my webpack, error(s) will be something else:. [Vue warn]: Error when rendering root instance. Uncaught TypeError: Cannot read property 'matched' of undefined. component.vue (with vue-loader):. Make sure, that loaders for *.styl, *.pug exist. UPDATE:I'm forget, than you can do it like this (without vue-loader):component.js.

インストール

Single File Components

Alex ShtorovAlex Shtorov. Vue-loader compiles .vue files into render functions, if you are not using them then you are going to need to use the standalone-build which includes the template compiler. As far as I'm aware that is the only difference between the runtime and standalone builds, so I see no reason why using the alias for the standalone build would not work in your case.

v-on Shorthand

Incidentally, .vue files can be split into multiple files. Take a look at the src imports section on this page, to see if it's something that would suit the requirements of your project. 55 gold badges5858 silver badges6767 bronze badges. 6767 bronze badges. 2021年10月 Stylelint v14リリースに伴って設定方法が変わったので編集しました。逆にStylelint v13未満を使用している場合この記事のStylelint設定手順ではうまくいかないことがあります。.

この記事は フューチャー Advent Calendar 2018 14日目の記事です。. 先週、Vue.jsのAdvent Calendarで「Vue.jsスタイルガイドとeslint-plugin-vue検証ルールのマッピング」という記事も書いたので興味があればこちらもよろしくお願いします。. Styling Vue components with CSS can help developers add design aesthetics to their applications, including background colors, font size, padding, positioning, animation, and responsive displays for different screen sizes.

With Vue directives, you can manage class and style binding within the template. You can also use inline styling within components, or use an external CSS file to keep our application organized.

Prerequisites

Conclusion

Use global styles in Vue.js

In this article, we will explore different ways of styling Vue components with CSS by building a simple web page.

Before going through this tutorial, there are a few things you should check for.

Text

Link with an external CSS file

First of all, you’ll need a code editor, preferably Visual Studio Code. Then, check that you have Node.js version 10.x or above installed by running the following in your terminal:.

You’ll also need Vue’s latest CLI. To get the latest version, uninstall the old CLI version first:. Then, install the latest version:. Alternatively, you can update the version like so:. The repo for for this demo can also be found here. I also recommend checking out a recent list of top Vue component libraries for further reading.

設定(config)

Inline Templates

To create a new project, run:. You will then be asked to pick a preset. You can either choose:. The default preset which comes with a basic Babel + ESLint setup. Vue 3 preview, or. Select “Manually select features” to pick the features you need.

Array syntax

Next, we will change directory:. And we will set ourselves up to view in a localhost :. The scoped attribute attached to the style tag below means that any CSS style defined here is only going to be applied to this template and not outside the component/template.

  • First, create a navbar component, named “Navbar”:.
  • In the example above, we created a navbar component.
  • Inside it, we used a scoped attribute to style the navbar.

This means that all the CSS styles defined here will only be applied in the navbar components.

As our application grows bigger with lots of CSS, I would recommend separating the CSS styles into an external CSS file and linking it to the component. This is just one of many ways to clean up your code. Here is an example:. Your above component will link to the external CSS file below:. When using an external file, you can either link it through the source file itself or import it in the style tag.

For this example, we linked the external CSS file that we created in the assets folder in our Vue application.

  • There are some styles that we will want to apply across components in our app. To do so efficiently, we will use global styling, rather than styling them in a scoped or external file (although this would work too).

  • If you want to do general styling like fonts, colors, background-color, border-radius, and margin, global styling is your best option. In our example below, we are going to add our global styling in our App.vue style tag.

Lint実行

Single-instance component names strongly recommended

As you will notice, we used a CSS wildcard selector (pronounced as an asterisk) to select all the element s in our application.

In this instance, the margin and padding on all elements has been set to 0, and box-sizing has been set to border-box . An inline CSS is used to apply a unique style to a particular HTML element using the style attribute. Here is a simple example:. In Vue.js, we can add an inline style to our element by binding the style attribute in the HTML tag.

Dynamic Argument Value Constraints

Tightly coupled component names strongly recommended

For reference, :style is shorthand for v-bind:style. Inline styling can be done in two ways: using object syntax or array syntax.

We will discuss both below. The object syntax allows us to use inline styling by putting the CSS attribute name as the key name of the object, and the values as the value of each CSS attribute.

Dynamic Argument Expression Constraints

When using object syntax, use either camelCase or “kebab-case,” as in the example below. In this instance, we created a footer component and then used the object syntax to style the footer element.

With the object syntax approach, it is a good practice to bind to a style object directly so that as our application gets bigger, our template will look cleaner.

Check it out in the following example:.

  • The other method of inline styling is to add multiple style objects with the array syntax.
  • In the following example, we will add an extra object in the array syntax — textColor — which will change the text color to red:.

Bad

Order of words in component names strongly recommended

When you want to add multiple style objects as shown in the example above, it is best to use the array syntax; to dynamically style classes, the object syntax is the best method for inline styling.

Detailed Explanation

In this tutorial, we learned about different ways that we can style our Vue.js application, including scoped styling, linking to external CSS files, global styling, and inline styling with object and array syntax.

We also made a simple website to illustrate how to apply the different styling methods.

In natural English, adjectives and other descriptors do typically appear before the nouns, while exceptions require connector words. For example:

  • Coffee with milk
  • Soup of the day
  • Visitor to the museum

You can definitely include these connector words in component names if you’d like, but the order is still important.

Also note that what’s considered “highest-level” will be contextual to your app. For example, imagine an app with a search form. It may include components like this one:

As you might notice, it’s quite difficult to see which components are specific to the search. Now let’s rename the components according to the rule:

Since editors typically organize files alphabetically, all the important relationships between components are now evident at a glance.

You might be tempted to solve this problem differently, nesting all the search components under a “search” directory, then all the settings components under a “settings” directory. We only recommend considering this approach in very large apps (e.g. 100+ components), for these reasons:

  • It generally takes more time to navigate through nested sub-directories, than scrolling through a single components directory.
  • Name conflicts (e.g. multiple ButtonDelete.vue components) make it more difficult to quickly navigate to a specific component in a code editor.
  • Refactoring becomes more difficult, because find-and-replace often isn’t sufficient to update relative references to a moved component.

Bad

Self-closing components strongly recommended

Components with no content should be self-closing in single-file components, string templates, and JSX - but never in DOM templates.

Components that self-close communicate that they not only have no content, but are meant to have no content. It’s the difference between a blank page in a book and one labeled “This page intentionally left blank.” Your code is also cleaner without the unnecessary closing tag.

Unfortunately, HTML doesn’t allow custom elements to be self-closing - only official “void” elements. That’s why the strategy is only possible when Vue’s template compiler can reach the template before the DOM, then serve the DOM spec-compliant HTML.

Bad

Component name casing in templates strongly recommended

In most projects, component names should always be PascalCase in single-file components and string templates - but kebab-case in DOM templates.

PascalCase has a few advantages over kebab-case:

  • Editors can autocomplete component names in templates, because PascalCase is also used in JavaScript.
  • is more visually distinct from a single-word HTML element than , because there are two character differences (the two capitals), rather than just one (a hyphen).
  • If you use any non-Vue custom elements in your templates, such as a web component, PascalCase ensures that your Vue components remain distinctly visible.

Unfortunately, due to HTML’s case insensitivity, DOM templates must still use kebab-case.

Also note that if you’ve already invested heavily in kebab-case, consistency with HTML conventions and being able to use the same casing across all your projects may be more important than the advantages listed above. In those cases, using kebab-case everywhere is also acceptable.

Bad

Component name casing in JS/JSX strongly recommended

Component names in JS/JSX should always be PascalCase, though they may be kebab-case inside strings for simpler applications that only use global component registration through Vue.component.

Detailed Explanation

In JavaScript, PascalCase is the convention for classes and prototype constructors - essentially, anything that can have distinct instances. Vue components also have instances, so it makes sense to also use PascalCase. As an added benefit, using PascalCase within JSX (and templates) allows readers of the code to more easily distinguish between components and HTML elements.

However, for applications that use only global component definitions via Vue.component, we recommend kebab-case instead. The reasons are:

  • It’s rare that global components are ever referenced in JavaScript, so following a convention for JavaScript makes less sense.
  • These applications always include many in-DOM templates, where kebab-case must be used.

Bad

Full-word component names strongly recommended

Component names should prefer full words over abbreviations.

The autocompletion in editors make the cost of writing longer names very low, while the clarity they provide is invaluable. Uncommon abbreviations, in particular, should always be avoided.

Bad

Prop name casing strongly recommended

Prop names should always use camelCase during declaration, but kebab-case in templates and JSX.

We’re simply following the conventions of each language. Within JavaScript, camelCase is more natural. Within HTML, kebab-case is.

Bad

Multi-attribute elements strongly recommended

Elements with multiple attributes should span multiple lines, with one attribute per line.

In JavaScript, splitting objects with multiple properties over multiple lines is widely considered a good convention, because it’s much easier to read. Our templates and JSX deserve the same consideration.

Bad

Simple expressions in templates strongly recommended

Component templates should only include simple expressions, with more complex expressions refactored into computed properties or methods.

Complex expressions in your templates make them less declarative. We should strive to describe what should appear, not how we’re computing that value. Computed properties and methods also allow the code to be reused.

Bad

Simple computed properties strongly recommended

Complex computed properties should be split into as many simpler properties as possible.

Detailed Explanation

Simpler, well-named computed properties are:

  • Easier to test

    When each computed property contains only a very simple expression, with very few dependencies, it’s much easier to write tests confirming that it works correctly.

  • Easier to read

    Simplifying computed properties forces you to give each value a descriptive name, even if it’s not reused. This makes it much easier for other developers (and future you) to focus on the code they care about and figure out what’s going on.

  • More adaptable to changing requirements

    Any value that can be named might be useful to the view. For example, we might decide to display a message telling the user how much money they saved. We might also decide to calculate sales tax, but perhaps display it separately, rather than as part of the final price.

    Small, focused computed properties make fewer assumptions about how information will be used, so require less refactoring as requirements change.

Bad

Quoted attribute values strongly recommended

Non-empty HTML attribute values should always be inside quotes (single or double, whichever is not used in JS).

While attribute values without any spaces are not required to have quotes in HTML, this practice often leads to avoiding spaces, making attribute values less readable.

Bad

Directive shorthands strongly recommended

Directive shorthands (: for v-bind:, @ for v-on: and # for v-slot) should be used always or never.

Bad

Priority C Rules: Recommended (Minimizing Arbitrary Choices and Cognitive Overhead)

Component/instance options order recommended

Component/instance options should be ordered consistently.

This is the default order we recommend for component options. They’re split into categories, so you’ll know where to add new properties from plugins.

  1. Side Effects (triggers effects outside the component)

    • el
  2. Global Awareness (requires knowledge beyond the component)

    • name
    • parent
  3. Component Type (changes the type of the component)

    • functional
  4. Template Modifiers (changes the way templates are compiled)

    • delimiters
    • comments
  5. Template Dependencies (assets used in the template)

    • components
    • directives
    • filters
  6. Composition (merges properties into the options)

    • extends
    • mixins
  7. Interface (the interface to the component)

    • inheritAttrs
    • model
    • props/propsData
  8. Local State (local reactive properties)

    • data
    • computed
  9. Events (callbacks triggered by reactive events)

    • watch
    • Lifecycle Events (in the order they are called)
      • beforeCreate
      • created
      • beforeMount
      • mounted
      • beforeUpdate
      • updated
      • activated
      • deactivated
      • beforeDestroy
      • destroyed
  10. Non-Reactive Properties (instance properties independent of the reactivity system)

    • methods
  11. Rendering (the declarative description of the component output)

    • template/render
    • renderError

Element attribute order recommended

The attributes of elements (including components) should be ordered consistently.

This is the default order we recommend for component options. They’re split into categories, so you’ll know where to add custom attributes and directives.

  1. Definition (provides the component options)

    • is
  2. List Rendering (creates multiple variations of the same element)

    • v-for
  3. Conditionals (whether the element is rendered/shown)

    • v-if
    • v-else-if
    • v-else
    • v-show
    • v-cloak
  4. Render Modifiers (changes the way the element renders)

    • v-pre
    • v-once
  5. Global Awareness (requires knowledge beyond the component)

    • id
  6. Unique Attributes (attributes that require unique values)

    • ref
    • key
  7. Two-Way Binding (combining binding and events)

    • v-model
  8. Other Attributes (all unspecified bound & unbound attributes)

  9. Events (component event listeners)

    • v-on
  10. Content (overrides the content of the element)

    • v-html
    • v-text

Empty lines in component/instance options recommended

You may want to add one empty line between multi-line properties, particularly if the options can no longer fit on your screen without scrolling.

When components begin to feel cramped or difficult to read, adding spaces between multi-line properties can make them easier to skim again. In some editors, such as Vim, formatting options like this can also make them easier to navigate with the keyboard.

Good

Single-file component top-level element order recommended

Single-file components should always order