Vue 'export default' vs 'new Vue'
I just installed Vue and have been following some tutorials to create a project using the vue-cli webpack template. When it creates the component, I notice it binds our data inside of the following:
export default {
name: 'app',
data: []
}
Whereas in other tutorials I see data being bound from:
new Vue({
el: '#app',
data: []
)}
What is the difference, and why does it seem like the syntax between the two is different? I'm having trouble getting the 'new Vue' code to work from inside the tag I'm using from the App.vue generated by the vue-cli.
Solution 1:
When you declare:
new Vue({
el: '#app',
data () {
return {}
}
)}
That is typically your root Vue instance that the rest of the application descends from. This hangs off the root element declared in an html document, for example:
<html>
...
<body>
<div id="app"></div>
</body>
</html>
The other syntax is declaring a component which can be registered and reused later. For example, if you create a single file component like:
// my-component.js
export default {
name: 'my-component',
data () {
return {}
}
}
You can later import this and use it like:
// another-component.js
<template>
<my-component></my-component>
</template>
<script>
import myComponent from 'my-component'
export default {
components: {
myComponent
}
data () {
return {}
}
...
}
</script>
Also, be sure to declare your data
properties as functions, otherwise they are not going to be reactive.
Solution 2:
export default
is used to create local registration for Vue component.
Here is a great article that explain more about components https://frontendsociety.com/why-you-shouldnt-use-vue-component-ff019fbcac2e