In Vue 3, component export is typically achieved using the export default syntax. This is because each Vue component is an independent module, and export default allows us to export a single value, which in most cases is the component object itself.
Within the <script> tag of a Vue 3 component, we typically define component options as an object (such as data, methods, computed, etc.), and export this object as the default module export. Here is a specific example:
vue<script> export default { name: 'MyComponent', data() { return { message: 'Hello from Vue!' } }, methods: { greet() { console.log(this.message); } } } </script>
In this example, we create a Vue component named MyComponent with a reactive data property message and a method greet. This component is exported using the export default syntax, allowing other files to use this component via import MyComponent from './MyComponent.vue'.
Advanced Usage
Beyond simply exporting an object, Vue 3 supports the use of the Composition API, which allows us to organize component logic more flexibly. When using the Composition API, we organize the code using the setup function, and the return value of the setup function determines what data and methods are available for the template. Here is an example using the Composition API:
vue<script> import { ref, onMounted } from 'vue'; export default { name: 'MyComponent', setup() { const message = ref('Hello from Vue with Composition API!'); onMounted(() => { console.log('Component is mounted'); }); // The object returned by the `setup` function determines which reactive data and functions can be accessed in the template return { message }; } } </script>
In this example, we use ref to create a reactive data property message, and log a message when the component is mounted. By returning message from the setup function, it becomes accessible in the component's template.
Summary
In Vue 3, setting up the default export within the script is primarily achieved through export default, regardless of whether using Options API or Composition API. This approach is concise and clear, making it well-suited for modern JavaScript's modular development.