Neha
Neha

Reputation: 2261

What should be structure of Vue component? in which order functions should be added?

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

Upvotes: 8

Views: 5898

Answers (3)

Satyam Pathak
Satyam Pathak

Reputation: 6912

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

Upvotes: 13

Estus Flask
Estus Flask

Reputation: 222503

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.

Upvotes: 2

Imre_G
Imre_G

Reputation: 2535

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.

Upvotes: 2

Related Questions