8

Is there any systematic structure for Vue component? In which order computed , methods, components, mounted watch etc should be written?

3 Answers 3

12

Update For component I mostly prefer putting script tags before html tags. As the idea that we mostly use to play with js so I feel itchy to move down always in the page. Else make your layout as per your preference

As per Vue official style guide -

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.

Side Effects (triggers effects outside the component)

el

Global Awareness (requires knowledge beyond the component)

name
parent

Component Type (changes the type of the component)

functional

Template Modifiers (changes the way templates are compiled)

delimiters
comments

Template Dependencies (assets used in the template)

components
directives
filters

Composition (merges properties into the options)

extends
mixins

Interface (the interface to the component)

inheritAttrs
model
props/propsData

Local State (local reactive properties)

data
computed

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

Non-Reactive Properties (instance properties independent of the reactivity system)

methods

Rendering (the declarative description of the component output)

template/render
renderError

For more recommended style-guide of Vue - Look here vue-style-guide

1
  • I suggest to use eslint-plugin-vue for your project it designed as per vue official guide - very helpful- Your welcome May 25, 2019 at 6:23
2

No, there is not. 100% personal preference. I like to start with the data, methods and usually end with the lifecycle methods. That is similar to how it is usually positioned in the docs and seems convenient because data and methods get changed a lot, and lifecycle methods not so much. However, there is no reason to do it like that from the framework. Go your game.

0
2

It's possible to maintain the order of object keys in practice in JavaScript, but this isn't guaranteed for ES5 specification, which is supported by Vue. So it shouldn't be expected that the framework will rely on the order in which component properties are defined.

Component functions can maintain a certain order for consistency like other answers explains, but they should not. This is purely a matter of style.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.