How to use a single-file Vue component
In many vue projects, we use vue. component to define global components, and then use new vue (el: ") to specify a container element on each page.
This method works well in many small and medium-sized projects, where JavaScript is only used to enhance specific views.
But when you block more complex projects or your front-end is fully driven by javascript, the following disadvantages will become very obvious:
- Global definition (global definition) requires that the names of each component cannot be repeated.
- The string template (string templates) lacks syntax highlighting. When html has multiple rows, the ugly \
- No CSS support means css is obviously omitted when html and javascript are componentized.
- No build step restrictions can only use html and es5 javascript, rather than pre-processors, such as pug (formerly jade) and babel
The sigle-file components (single file component) with the file extension. vue provides a solution to all of the preceding problems. You can also use build tools such as webpack or browserify.
This is a simple instance named hello. vue.
<template> <p> {{ gretting}} world! </p></template><script> module.exports = { data: function(){ return { greeting: 'hello' } } }</script><style scoped>p { font-size: 2em; text-algin: center}</style>
Now we get:
- Complete syntax highlighting
- CommonJs Template
- Componentized css
As we have said, we can use pre-processors to build concise and more functional components, such as pug, babel, and stylus.
<template lang="jade"> div p {{greeting}} world! other-component </template><script> import default{ data(){ return{ greeting:'hello' } }, components: { OtherComponent } }</script><style lang='stylus' scoped> p font-size: 2em; text-align: center </style>
These specific languages are just examples. You can simply use Babel, TypeScript, SCSS, PostCSS-or any other Preprocessor that can help you increase productivity. If you use Webpack with vue-loader, CSS Modules is treated as the first citizen.
What is the separation of concerns?
One important thing worth noting is that separation of focus is not equal to separation of file types.
In modern UI development, we have found that, compared with separating code libraries into three major layers and intertwined them, divide them into loosely coupled components and then combine them more rationally.
In a component, the template, logic, and style are internally coupled, and the combination of them actually makes the component more cohesive and maintainable.
Even if you do not like single-file components, you can still separate JavaScript and CSS into independent files and perform hot reloading and pre-compilation.
<!-- my-component.vue --><template> <div>This will be pre-compiled</div></template><script src="./my-component.js"></script><style src="./my-component.css"></style>
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.