Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to get different resources and switch pictures according to the theme in Vue

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to get different resources to switch pictures according to the theme in Vue". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to get different resources to switch pictures according to the theme in Vue".

Recently, one of the company's Mini Game Y needs to achieve a localized theme, that is, different regions need to show different themes, and there are many pictures of the game, how to load the right skin pictures elegantly and quickly has become particularly important.

There are many solutions in the css style switching community, which can be referenced by yourself. This article has been described in great detail. I will not repeat it here. This article will mainly talk about how to get different resources to switch pictures according to the topic.

Initial plan

Picture skinning, according to past experience, thanks to the dependency management of webpack, we usually use require to introduce pictures. For example, in this way of writing (require (`@ assets/img/$ {theme} / bg.png`)), webpack adds all the files in @ assets/img to the bundle so that the corresponding images can be found at run time. The specific implementation is as follows:

Data: () = > ({theme: 'blcak'}), computed: {contentBg () {try {/ / this.theme is a folder, put different skins into different folders, and use the same name return require (`@ assets/img/$ {this.theme} / contentBg.png`)} catch (err) {return'' }}, rewardImg () {try {return require (`@ assets/img/$ {this.theme} / rewardImg.png`)} catch (err) {return';}

The above code can basically solve most of the skinning needs, but for projects where images need to be preloaded, we also need to distinguish between images of different themes to optimize and load ahead of time. Because the compiled picture link is different from the pre-compiled link, so we get the compiled picture link. In a general project, such as a project built using official scaffolding vue-cli, all images will be processed by url-loader and put into the same folder image, so that before compilation, the hash of images with the same name in different folders will be different after compilation, so we cannot distinguish between pictures of different themes.

So, first of all, we need to put different theme pictures in different folders, which is also applicable to url-loader.

/ / vue-cli configuration const imagesRule = config.module.rule ('images') ImagesRule.uses.clear () / clear the original images loader configuration imagesRule. Test (/ white/.+. (jpg | gif | png | svg) $/) .use ('url-loader') .loader (' url-loader') .options ({name: "img/white/ [name]. [hash: 8]. [ext]" Limit: 8192}) / / add config.module .rule ('image2'). Test (/ black/.+. (jpg | gif | png | svg) $/) .use (' url-loader') .loader ('url-loader') .options ({name: "img/black/ [name]. [hash: 8]. [ext]", limit: 8192}) / Custom webpack configuration rules: [{test: / white/.+. (png | svg | jpg | gif) $/ Use: [{loader: 'url-loader', options: {limit: 8192, name:' img/white/ [name]. [hash: 8] .[ ext],}}],}, {test: / black/.+. (png | svg | gif) $/, use: [{loader: 'url-loader' Options: {limit: 8192, name: 'img/black/ [name]. [hash: 8] .[ ext],}}],},]

In this way, the compiled pictures of different themes will be placed in different folders, so it's over? Not yet, we also need to get the link to the compiled images in order to load the theme images in advance when entering the game page. Here we can write a webpack plugin to help us collect the corresponding pictures and produce the json files of their respective themes. The plug-in code is as follows:

/ / webpack version is 4.xclass WebPackSouceManifest {/ / define `apply` as its prototype method This method takes compiler as the parameter constructor (option = {}) {/ / black theme file name this.blackManifestName = option.blackManifestName | | 'js/blackManifest.json' / / white theme file name this.whiteManifestName = option.whiteManifestName | |' js/whiteManifest.json' this.blackJsonData = {code: 0, data: []} this.whiteJsonData = {code: 0 Data: []} this.addFileToSouceManifest.bind (this)} apply (compiler) {/ / specify the event hook function compiler.hooks.emit.tapAsync ('HashServiceWorkerStartPlugin', (compilation) to attach to Callback) = > {const allBuildFiles = Object.keys (compilation.assets) allBuildFiles.forEach ((file) = > {if (file.indexOf ('white')! =-1) {this.addFileToSouceManifest (' white', file)} else {this.addFileToSouceManifest ('black') File)}}) const sourceBlack = JSON.stringify (this.blackJsonData) const sourceWhite = JSON.stringify (this.whiteJsonData) compilation.assets [this.blackManifestName] = {source: () = > {return sourceBlack }, size: () = > {return sourceBlack.length;}} compilation.assets [this.whiteManifestName] = {source: () = > {return sourceWhite;}, size: () = > {return sourceWhite.length;}} callback ()}) } addFileToSouceManifest (type, file) {let fileItem = {src: file } if (/ .js $/ .test (file)) {fileItem.type = 'text'} else if (/ .js.map $/ .test (file)) {fileItem.type =' json'} if (type = 'white') {this.whiteJsonData.data.push (fileItem)} else {this.blackJsonData.data.push (fileItem)}} module.exports = WebPackSouceManifest

So we get the picture list json of different themes, and when we enter the page, we load the pictures in the other table after getting the list through ajax. Although the above approach can achieve the requirements, it is too complicated. Is there an easy way to do that? Of course there is.

Optimization scheme

After carefully analyzing the above code, we will finally get the compiled result of the image, so if we can generate an image object and treat the name of the image as key and the compiled result as value, then the above code can be simplified as follows:

Data: () = > ({theme: 'middleEast'}), computed: {contentBg () {/ / skinImage is the field under the component return this.$root.skinImage [' contentBg'] / / contentBg is name}, rewardImg () {return this.$root.skinImage ['rewardImg']}}

So the code becomes concise and does not need the whole require and try catch, so how do we implement this skinImage object?

The answer is to use webpack's require.context.

Get a specific context by executing the require.context function, which is mainly used to implement the automatic import module. In the front-end project, if you encounter a situation in which many modules are imported from a folder, you can use this api. It will traverse the specified files in the folder and then import automatically, so that you do not need to explicitly call the import import module every time. The specific usage will not be discussed here.

For details, please see the official document requirecontext.

Https://webpack.docschina.org/guides/dependency-management/#requirecontext

So let's write a function that automatically imports pictures and generates skinImage objects.

Const black = require.context ('.. / black', true, /. (png | jpg | gif) $/); const middleImageObj = {}; black.keys (). ForEach (path = > {/ / key const key = path.slice (2,-4); blackImageObj [key] = rawSkin (path);})

In this way, we get the picture object of the black theme. Since the execution of require.context is in the compilation process rather than at run time, all parameters can only be static. Here, we also need to get the picture of the white theme in advance, as follows.

Const black = require.context ('.. / black', true, /. (png | jpg | gif) $/); const middleImageObj = {}; black.keys (). ForEach (path = > {/ / key const key = path.slice (2,-4); blackImageObj [key] = rawSkin (path);})

In this way, we get the picture objects of the two themes, and then we just assign a certain object to the skinImage of the root component, and we're done. Is it simpler and more concise than the one above?

Thank you for your reading, the above is the content of "how to get different resources to switch pictures according to the theme in Vue". After the study of this article, I believe you have a deeper understanding of how to get different resources to switch pictures according to the theme in Vue, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report