In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "what is the reason for the slow use of fengMap in vue". The editor shows you the operation process through an actual case, the operation method is simple and fast, and it is practical. I hope this article "what is the reason for the slow use of fengMap in vue" can help you solve the problem.
Reasons for slow use of fengMap
Objects in fengMap cannot be placed in vue data. Using let to declare variables in script can avoid the problem of being too slow.
Import FengMap from'@ / components/Geo/fengmap'let map = {fengMap: undefined, lastCheckModel: undefined,}
Error code
Export default {data () {return {map: {fengMap: undefined, lastCheckModel: undefined,} some tips on the use of vue
In the use of vue will encounter a variety of scenarios, when the general use of feel nothing, but perhaps optimize the development can be more efficient and more beautiful.
1. Multi-graph resize event decentralization
1.1 General situation
Sometimes we encounter scenarios where there are several diagrams in a component, and we want the diagrams to be resize in the browser resize, so we write in the parent container component:
Mounted () {setTimeout (() = > _ window.onresize = () = > {this.$refs.chart1.chartWrapperDom.resize () this.$refs.chart2.chartWrapperDom.resize () /...}, 200) destroyed () {_ window.onresize = null}
In this way, if the chart component is not on the same page as the parent container component, the state of the child component will be managed by the parent component. For convenience of maintenance, we naturally want the events and state of the child component to be maintained by ourselves. In this way, when adding and deleting components, there is no need to go to the parent components to modify them one by one.
1.2 Optimization
Here the use of lodash throttling throttle function, you can also implement their own, this article also has a throttling implementation to refer to. Take Echarts as an example, in each chart component:
Computed: {/ * Chart DOM * / chartWrapperDom () {const dom = document.getElementById ('consume-analy-chart-wrapper') return dom & & Echarts.init (dom)}, / * * Chart resize throttling, lodash is used here You can also use setTimout to achieve throttling * / chartResize () {return _ .throttle (() = > this.chartWrapperDom & & this.chartWrapperDom.resize (), 400)}, mounted () {window.addEventListener ('resize', this.chartResize)}, destroyed () {window.removeEventListener (' resize', this.chartResize)} 2. Global filter registration
2.1 General situation
How to officially register the filter:
/ / register Vue.filter ('my-filter', function (value) {/ / return the processed value}) / / getter, and return the registered filter var myFilter = Vue.filter (' my-filter')
But decentralized writing is not beautiful, so it can be extracted into a separate file.
2.2 Optimization
We can extract it to a separate file and use Object.keys to register / src/common/filters.js uniformly at the main.js entry
Let dateServer = value = > value.replace (/ (\ d {4}) (\ d {2}) (\ d {2}) / g,'$1) export {dateServer} / src/main.jsimport * as custom from'. / common/filters/custom'Object.keys (custom) .forEach (key = > Vue.filter (key))
Then we can happily use these global filters that we have defined in other. Vue files
{{time | dateServer}}
Export default {data () {return {time: 20160101} 3. Global component registration
3.1 General situation
Scenarios where you need to use components:
Import BaseButton from'. / baseButton' import BaseIcon from'. / baseIcon' import BaseInput from'. / baseInput' export default {components: {BaseButton, BaseIcon, BaseInput}}
We've written a bunch of basic UI components, and every time we need to use these components, we have to import them first, and then declare components, which is tedious, and we can use unified registration here.
3.2 Optimization
We need to use the artifact webpack and use the require.context () method to create our own module context to implement automatic dynamic require components. This method requires three parameters: the folder directory to be searched, whether its subdirectories should also be searched, and a regular expression that matches the file. We add a file called componentRegister.js in the components folder, where webpack dynamically packages all the basic components we need. / src/components/componentRegister.js
Import Vue from 'vue'/** * capital * @ param str string * @ example heheHaha * @ return {string} HeheHaha * / function capitalizeFirstLetter (str) {return str.charAt (0). ToUpperCase () + str.slice (1)} / * * take the component name * @ param str fileName * @ example abc/bcd/def/basicTable.vue * @ return {for components that conform to the' xx/xx.vue' component format String} BasicTable * / function validateFileName (str) {return / ^\ S+\ .vue $/ .test (str) & & str.replace (/ ^\ S+\ / (\ w+)\ .vue$/ (rs, $1) = > capitalizeFirstLetter ($1)} const requireComponent = require.context ('. /', true, /\ .vue $/) / / find the file named .vue under the component folder If the file name is index, then take the name in the component as the registered component name requireComponent.keys () .forEach (filePath = > {const componentConfig = requireComponent (filePath) const fileName = validateFileName (filePath) const componentName = fileName.toLowerCase () = = 'index'? CapitalizeFirstLetter (componentConfig.default.name): fileName Vue.component (componentName, componentConfig.default | | componentConfig)})
Here is the folder structure:
Components │ componentRegister.js ├─ BasicTable │ BasicTable.vue ├─ MultiCondition │ index.vue
The component name is judged here. If it is index, the name attribute in the component is taken and processed as the registered component name, so the final registered components are: multi-condition, basic-table, and finally we import 'components/componentRegister.js', in main.js, and then we can use these basic components anytime, anywhere, without the need to manually introduce ~
4. Component reuse of different routes
4.1 scene restore
When vue-router is from / post-page/an in a scene, jump to / post-page/b. Then we were surprised to find that the data was not updated after the page jumped. The reason is that vue-router "intelligently" discovers that this is the same component, and then it decides to reuse the component, so the method you wrote in the created function is not executed at all. The usual solution is to listen for changes in $route to initialize the data, as follows:
Data () {return {loading: false, error: null, post: null}}, watch: {'$route': {/ / use watch to monitor whether it is the same route handler: 'resetData', immediate: true}}, methods: {resetData () {this.loading = false this.error = null this.post = null this.getPost (this.$route.params.id)}, getPost (id) {}}
4.2 Optimization
So how can we achieve this effect? the answer is to add a different key to router-view, so that even if it is a common component, as soon as the url changes, it will be recreated.
You can also add a + + new Date () timestamp after it to ensure uniqueness.
5. High-order component
5.1 General situation
/ / parent component / / Child component {{label}}
5.2 Optimization
1 every props passed from the parent component to the child component can only be used by explicitly declaring it in the Props of the child component. As a result, our child components need to declare a lot of props at a time, and we can actually use $attrs to pass directly from parent to child with a native dom property like placeholer, without declaration. The methods are as follows:
Attrs contains feature bindings in the parent scope that are not recognized (and acquired) as prop (except for class and style). When a component does not declare any prop, all parent scope bindings are included here, and internal components can be passed in via vmurbind = "$attrs"-- useful when creating higher-level components.
2 notice that the @ focus= "$emit ('focus', $event)" of the child component actually does nothing but passes the event back to the parent component, which is similar to the above, and there is no need to explicitly state:
Computed: {listeners () {return {... this.$listeners, input: event = > this.$emit ('input', event.target.value)}
Listeners contains the v-on event listeners in the parent scope (without the .native modifier). It can pass in internal components via vMuon = "$listeners"-- useful when creating higher-level components.
It should be noted that since we, input, are not the root node of the BaseInput component, feature bindings of the parent scope that are not considered props by default will be "fallback" and applied to the root element of the child component as a normal HTML feature. So we need to set inheritAttrs: false, and these default behaviors will be removed for the above two optimizations to be successful.
6. Routes load lazily according to development status
6.1 General situation
Usually when we load a component in a route:
Import Login from'@ / views/login.vue'export default new Router ({routes: [{path:'/ login', name: 'login', component: Login}]})
When you need to load lazy-loading lazily, you need to change the component of routes to () = > import ('@ / views/login.vue') one by one, which is troublesome.
As you have more and more project pages, it becomes inappropriate to use lazy-loading in the development environment, and updates become very slow every time the code changes. Therefore, it is recommended that you use the routing lazy loading feature only in the build environment.
6.2 Optimization
Lazy loading of components can be easily realized according to the asynchronous components of Vue and the code segmentation function of Webpack, such as:
Const Foo = () = > import ('. / Foo.vue')
When distinguishing between a development environment and a production environment, you can create two new files under the routing folder: _ import_production.js
Module.exports = file = > () = > import ('@ / views/' + file + '.vue')
_ import_development.js, the vue-loader version is at least v13.0.0 or above
Module.exports = file = > require ('@ / views/' + file + '.vue') .default
In the router/index.js file that sets the route:
Const _ import = require ('. / _ import_' + process.env.NODE_ENV) export default new Router ({routes: [{path:'/ login', name: 'login', component: _ import ('login/index')}]})
In this way, components are not lazily loaded in the development environment and lazily loaded in the production environment.
7 vue-loader Tips
Vue-loader is the webpack loader that handles * .vue files. It itself provides a wealth of API, some of which are useful but rarely known. For example, preserveWhitespace and transformToRequire will be introduced next.
7.1 reduce file size with preserveWhitespace
Sometimes when we write a template, we don't want a space between the element. It might look like this:
11112222333
Of course, there are other ways, such as setting the font font-size: 0, and then setting the font size separately for the desired content, in order to remove the spaces between elements. In fact, we can achieve this requirement by configuring vue-loader.
{vue: {preserveWhitespace: false}}
Its purpose is to prevent blank content from being generated between elements, which is represented by _ v ("") after the Vue template is compiled. If there are a lot of templates in the project, they will still take up some file volume. For example, after Element configures this attribute, the file size is reduced by nearly 30Kb without compression.
7.2 using transformToRequire, you no longer have to write pictures as variables.
In the past, when writing Vue, we used to write code like this: require the picture in advance to a variable and then pass it to the component.
Export default {created () {this.DEFAULT_AVATAR = require ('. / assets/default-avatar.png')}}
In fact, after configuring transformToRequire, you can configure it directly, so that vue-loader will automatically require the corresponding properties and pass them to the component.
{vue: {transformToRequire: {avatar: ['default-src']}
So our code can be simplified a lot.
Under the webpack template of vue-cli, the default configuration is:
TransformToRequire: {video: ['src',' poster'], source: 'src', img:' src', image: 'xlink:href'}
You can use examples to make a similar configuration.
Vue-loader also has a lot of useful API, such as the recently added custom blocks, interested people can look in the documentation.
8. Render function
In some scenarios you may need the full programming capabilities of render rendering functions to solve problems that are not easy to solve, especially to dynamically select scenarios that generate tags and component types.
8.1 dynamic label
1. General situation
For example, a scenario in which tags are generated based on props
Where level is a variable in data, you can see that there is a lot of repetitive code here. If the logic is more complex and some binding and judgment are added, you can use the render function to judge the tag to be generated.
two。 Optimize
Using the render method to generate corresponding tags based on parameters can avoid the above situation.
Hello world! Import Vue from 'vue' Vue.component (' child', {render (h) {const tag = ['div',' packs, 'strong',' H2, 'h3percent,' textarea'] [this.level] return h (tag, this.$slots.default)}, props: {level: {type: Number, required: true}}}) export default {name: 'hehe', data () {return {level: 3}
8.2 dynamic components
Of course, there are many uses of the render function, for example, to use dynamic components, in addition to using: is, you can also use the render function
Import Vue from 'vue' import Xixi from'. / Xixi' import Haha from'. / Haha' Vue.component ('child', {render (h) {const tag = [' xixi', ''] [this.level] return h (tag, this.$slots.default)}, props: {level: {type: Number, required: true}}, components: {Xixi, Haha}}) export default {name:' hehe' Data () {return {level: 0} on "what is the reason for the slow use of fengMap in vue"? Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.