I'm coming from a Laravel blade background where I can slice a bigger chunk of my codes out, and import them back in one by one like so, and it will behave the same;
Ex.
My vue file now is reaching ~2000 lines of codes now, and it' getting very hard to work with.
Can someone please show me how to slice out some codes and import it back in and achive the same functionality?
CodePudding user response:
As per my understanding you want to reduce the number of lines of code from the single file. If Yes, I am here giving you an example of how you can do that for CSS styles. For JavaScript/Components, you can achieve by breaking the large feature/functionality into chunks by creating a separate utility/components.
Styling with external CSS files
You can include external CSS files and apply them globally to your app. Let me explain with an example, You have common theme for the application then you can add all the styles for that theme in a theme.css
file in the src/assets
directory. Files in this folder get processed automatically by Webpack.
Next, in your src/main.js
file, import the theme.css
file like so :
import '@/assets/theme.css';
The theme styles should be applied to the app now. Hence, no need to add the styles inside the components separately.
Why scoped styles ?
If You want to add any customization in the style at component level then you can add scoped
styles. To keep the style definitions close to the component we can add a element inside it with scoped
attribute.
<style scoped>
</style>
As per the author comment - I have issues with similar HTML codes and when I don't know how to move them over properly and include them back in without missing variables errors
Best practice is to construct your application in small, modular blocks of code. It makes the application easier to update as it grows in complexity. You can create a small .vue
components which contains their own HTML <template>
, <script>
, and <style>
tags and can be implemented in other components instead of putting whole functionality code into a single .vue
file.
CodePudding user response:
The answer would be to extract sub-components from your big-component and import them in your big component to make it shorter.
A good rule of thumb in programming in general, is that if code repeats it can be modularized. In the case of Vue, this can be achieved by putting repeating pieces of code in components.
The parts that slightly differ can be made into props that you can pass into these components.
Another rule would be that if you have a huge v-if/v-else that both render huge parts of code under each, the contents under each can be extracted as separate components.
I would suggest you read more of the following: https://vuejs.org/guide/essentials/component-basics.html https://vuejs.org/guide/components/props.html