Examples of common code extraction in vue. js and vue. js
Preface
When we use vue to build medium and large projects, we usually encounter some frequently used methods and attributes. For example, to build an employee management system, the requested url requires a common prefix, or it takes time in several views. This time is formatted by some method. If you write common code every time you use it, in this way, maintenance will be very troublesome if there are changes later.
Therefore, we have to find a way to extract public code. Because vue is a componentized development, we will naturally be associated with the module modularization of es6. In fact, when we build a project structure, we should first bury the foreshadowing in advance. There is an util folder which contains the public code we want to write, in fact, many vue examples are similar to this structure.
For fixed configuration parameters, we can put them in config. js, as shown below.
const config = { request_prefix: 'http://localhost:10003', base_img: 'http://www.baidu.com', }const DingConf = function(data){ xxxxxxxxx}export {config, DingConf}
Common tool functions can be put in util. js with the same structure as above.
Then why should I use export for export insteadexport default
What about it?
Because the former is more flexible, because for large and medium-sized projects, we usually have many tool functions and configuration parameters. If we useexport default
If you export the data, you can introduce all the data in the component. However, you only need to import the data on the corresponding page as needed. Therefore, in the vue file, you can write the data in this way.
Import {config} from 'src/util/config' // import module export default {created () {this. $ http ({url: config. request_prefix + xxxxxxxxxxxxx // use })}}
This mode enhances readability and facilitates maintenance. If some students do not quite understand the import and export in es6, I suggest you take a look at the es6 getting started tutorial of Ruan Yifeng. Here I will also give a brief introduction, because vue is modular, therefore, we have to export some things, and each module is only responsible for different services. So we have to use export at last. Because const is a constant, we should use this in configuration items as much as possible, declare the variable with let in the tool function, and then import {...} this is to introduce certain attributes or methods of a module. from 'xxx', this refers to the introduced module.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.