Home Web Front-end JS Tutorial Vue skin changing function example tutorial

Vue skin changing function example tutorial

Jan 26, 2018 am 10:43 AM
Function Example Tutorial

I have been working on a small mobile demo of Vue for a few months recently, one of which implements the unified skinning function of each page. This article mainly introduces the sample code of the skin-changing function based on Vue. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to have a look.

Let’s take a look at the implementation first

Set the theme color

It makes sense for such a function, I I think these points can be discussed and implemented step by step:

1. Selection of color values

2. Some niche usages of scss (batch setting of multi-variable CSS values)

3. Application of Global Event Bus

1 Selection and Principles of Color Value

It is recommended that you read the design guidelines of Ant Financial, which covers common There is a good set of guidelines and suggestions for interaction and interface design. Those who like reading can also read "Design Book for Everyone".

For color elements in the interface, we generally need to maintain visual continuity, that is, the same set of colors, and try to use the color values ​​on the same color wheel

The color values ​​on the same ring will appear more coordinated as a set of colors

So here we adopt the suggestion of ant design and take a certain column of color values ​​as the theme color of our series (the specific color value refers to its Official website~)

In some special occasions, it is necessary to show the difference in color, such as the two colors on the coin tossing page,

2 Convert the format color value into a hexadecimal color value

Here we distinguish different colors by setting the transparency of the theme color, and then we pass Store a hexadecimal color global variable such as #123456 as our theme. Here we need to convert the color value in such a format into a color value represented by rgba. The code is as follows, for backup


hexToRgba (hex, opacity = 0.3) {
  let color = []
  let rgb = []
  hex = hex.replace(/#/, '')
  for (let i = 0; i < 3; i++) {
   color[i] = &#39;0x&#39; + hex.substr(i * 2, 2)
   rgb.push(parseInt(Number(color[i])))
  }
  return `rgba(${rgb.join(&#39;,&#39;)},${opacity})`
 }
Copy after login

3 Some niche uses of scss

We finally got such a list of theme colors we wanted

Copy code The code is as follows:


$colors: #f04134, #00a854, #108ee9, #f5317f, #f56a00, #7265e6, #ffbf00, #00a2ae, #2e3238;

A very straightforward idea, we need to define the color of the elements we need to set the theme in each view page, such as the color of text and icon, and the background of the header, etc. So we define a color variable in the app and distribute it to each view component. We use this global variable to control the color of all routing pages to achieve different theme effects.

The implementation of distribution will be discussed in the next section. Here we will complete our first step. We can easily extract our requirements:

4 Set and save a global color

Little things about the interface:

I implemented this function directly on the homepage. In the project, I introduced the mint-ui framework (the mobile framework of the Ele.me team, which is a bit regretful to use) Not as comfortable as element.ui), the set interaction is in the form of elastic layer mt-popup, and then directly click on the color block to set the corresponding color value


<!-- 設置顏色 -->
  <mt-popup v-model="changColor" position="bottom" class="color-panel">
   <p class="color-items">
     <span class="color-item" v-for="(item, $index) in colors" :key="$index" @click="chooseColor(item)">
      <span class="color-cycle" :class="&#39;bg-color&#39; + ($index + 1)"></span>
      </span>
   </p>
  </mt-popup>
Copy after login

Then It is the presentation of the color block p. From the above code, I can easily find a css style sheet like this


.bg-color1 {background: #f04134}
.bg-color2 {background: #f04134}
.bg-color3 {background: #f04134}
.bg-color4 {background: #f04134}
···
Copy after login

When writing code, if we generally find that something like this When something reappears, I always feel that it is ready to start performing. And it is foreseeable that this situation means that after the project grows, there may be many style sheets that set the font color or border color alone, such as color1, borderColor1 ···In this way, we need to write each form of expression according to our theme color array one by one, and the modification cost will also become high. So my writing style is like this,


// mixin.scss:
$colors: #f04134, #00a854, #108ee9, #f5317f, #f56a00, #7265e6, #ffbf00, #00a2ae, #2e3238;

// setColor.vue:
@import &#39;~@/assets/mixin.scss&#39;;
···
@for $i from 1 to 10 {
    .bg-color#{$i} {
     background-color: nth($colors, $i)
    }
   }
Copy after login

scss In addition to the commonly used nested writing of class names, there are also many... low-key and luxurious syntax. For this kind of For style types that need to be written repeatedly, my convention is to add a scss variable in the mixin file, introduce it as a variable when writing a repeated loop style, and use the sass loop to reference the corresponding value when writing the style, so that no matter How to expand and change the color setting style, whether it is a color background border, I only need to maintain the color values ​​​​in a mixin file. The same practice can also be applied to the font size and spacing values ​​​​in the project. Unification and the like, let’s try to experience it more

5 Little things about logic

这个项目里面localstorage 基本被当成数据库使用了,所以点击色块设置主题时候,我们假装发出请求,在localstorage存储我们改变的颜色就好了( ./static/api.json 是一个返回helloword 的json, 为了写实在这里这么用,$bus 事件巴士下面说, 作用就是设置全局的主题颜色变量,localStorage 模拟我们把设置存储到后台,每次重新打开页面就去获取这些设置值), 目前为止,我们的设置页面就大致完成了


// 假装调用接口设置颜色
  chooseColor (color) {
   this.$axios.get(&#39;./static/api.json&#39;)
    .then((data) => {
     this.$bus.$emit(&#39;set-theme&#39;, color)
     this.changColor = false
     localStorage.setItem(&#39;themeColor&#39;, color)
    })
    .catch((data) => {
     console.log(data)
    })
  }
Copy after login

6 事件巴士的运用

在上一步最后我们有个关键的东西没完成, this.$bus.$emit('set-theme', color) ,将选取的颜色设置到全局,我的代码结构是这样的

子组件

是 home 页面 的一个子组件,而在一开始我们已经说了,我们想在我们在app.vue (home.vue和其他view的父组件) 里面定义一个color变量,派发到各个view组件里面去。 于是这其实就是个,从 setColor 触发 app.vue 的设置颜色事件, 子组件向父组件通信的问题。

我们可以很直接地用绑定事件配合 emit() 的做法,在 app.vue 定义一个 setglobalColor 方法, 并绑定到router-view(包含了home.vue),接着在home组件继续定义一个 setglobalColor 方法, 实现的功能就是 emit('setglobalColor') 去触发app.vue的方法, 并把 home.vue 的这个 setglobalColor 继续绑定到组件, 组件里面点选颜色时候,直接emit这个方法就行了。

为什么我想用事件巴士.vue 的事件巴士和 vuex, 在一些有追求的程序员手里总是小心翼翼的,我也一样,因为作为涉及全局的东西,一般觉得能不用就不用,代码能精简就精简,我们经常用一个词,不提倡。

可是有朝一日我经常在想,代码的可读性可维护性,和性能以及“风险”相对比,到底哪个更重要。对于事件巴士和vuex 这类全局性质的方案的主要担忧大部分在于, 他们是全局的,可能因为一个事件名变量名一致就造成冲突,在小型项目还会造成冗余和额外开销。 但事实上,事件和变量的命名我们都可以通过约定去规范,而在表现上,使用了事件巴士和vuex的项目,在性能上和直接 props 传递数据,emit 回调事件的项目相比,其实并没有太大区别,反而是无止境的 props 和 emit ,给人一种麻烦难以维护的感觉。 像上述的 setglobalColor , 仅仅是跨越了两层组件, 过程就显得繁琐了。所以我建议在出现两级以上组件层次,数据流稍微多的项目中都可以这么去做,定义一个全局的事件巴士


export default (Vue) => {
 let eventHub = new Vue()
 Vue.prototype.$bus = {
  $on (...arg) {
   eventHub.$on(...arg)
  },
  $off (...arg) {
   eventHub.$off(...arg)
  },
  $emit (...arg) {
   eventHub.$emit(...arg)
  }
 }
}
Copy after login

将事件巴士绑定到当前vue对象,使用时候只需要:


this.$bus.$on(&#39;set-theme&#39;, (color) => {··· })
this.$bus.$emit(&#39;set-theme&#39;, &#39;#000000&#39;)
Copy after login

在这个demo中,我在app.vue 绑定了


this.$bus.$on(&#39;set-theme&#39;, (color) => {
   this.loadingColor = color
   this.userinfo.color = color
  })
Copy after login

而在 setColor.vue 则在点击颜色块时候触发 this.$bus.$emit('set-theme', color), 则能实现我们设置全局颜色的效果。这样的好处在于,对于跨了多个层次,或者兄弟组件的通信,我们不再需要太繁琐的props,比如我在header.vue 也绑定了 this.$bus.$on('set-theme', (color) => { }) ,在 this.$bus.$emit 发生时候,header 的背景颜色就能直接改变,而不需要等待app.vue 将 全局的color值props传递到header.vue里面(仅做示例,这里 header.vue 只是 app.vue 的下一层级,通过props数据流会更清晰)

而对于其他路由页面组件,和 app.vue 都是直接上下级关系,我们依然采用props保持一个清晰的数据流向下传递, demo 里我是将 color 存在userinfo(以后还有其他数据), userinfo传到每个子路由, 最后,每个页面在创建时候,通过拿到这个全局的颜色,再用dom去更改对应的样式就好啦,例如


mounted () {
  this.$nextTick(() => {
   // 绑定设置主题的事件,一旦触发修改主题,则将当前字体颜色改为对应颜色
   this.$el.querySelector(&#39;.myTitle&#39;).style.color = this.userinfo.color
   this.$el.querySelector(&#39;.weui-btn_primary&#39;).style.backgroundColor = this.userinfo.color
   this.$el.querySelector(&#39;.add_icon&#39;).style.color = this.userinfo.color
  })
 }
Copy after login

详细的实现请参照项目代码,这里我只挑一些比较清奇的点出来讨论,项目和代码的一些规范和习惯还是挺重要的,希望有好的实践能互相借鉴进步~

相关推荐:

jQuery结合jQuery.cookie.js插件实现换肤功能示例

Javascript结合css实现网页换肤功能_javascript技巧

JQuery 网站换肤功能实现代码_jquery

The above is the detailed content of Vue skin changing function example tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tutorial on how to use Dewu Tutorial on how to use Dewu Mar 21, 2024 pm 01:40 PM

Dewu APP is currently a very popular brand shopping software, but most users do not know how to use the functions in Dewu APP. The most detailed usage tutorial guide is compiled below. Next is the Dewuduo that the editor brings to users. A summary of function usage tutorials. Interested users can come and take a look! Tutorial on how to use Dewu [2024-03-20] How to use Dewu installment purchase [2024-03-20] How to obtain Dewu coupons [2024-03-20] How to find Dewu manual customer service [2024-03-20] How to check the pickup code of Dewu [2024-03-20] Where to find Dewu purchase [2024-03-20] How to open Dewu VIP [2024-03-20] How to apply for return or exchange of Dewu

The difference between vivox100s and x100: performance comparison and function analysis The difference between vivox100s and x100: performance comparison and function analysis Mar 23, 2024 pm 10:27 PM

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

What exactly is self-media? What are its main features and functions? What exactly is self-media? What are its main features and functions? Mar 21, 2024 pm 08:21 PM

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

In summer, you must try shooting a rainbow In summer, you must try shooting a rainbow Jul 21, 2024 pm 05:16 PM

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

What software is photoshopcs5? -photoshopcs5 usage tutorial What software is photoshopcs5? -photoshopcs5 usage tutorial Mar 19, 2024 am 09:04 AM

PhotoshopCS is the abbreviation of Photoshop Creative Suite. It is a software produced by Adobe and is widely used in graphic design and image processing. As a novice learning PS, let me explain to you today what software photoshopcs5 is and how to use photoshopcs5. 1. What software is photoshop cs5? Adobe Photoshop CS5 Extended is ideal for professionals in film, video and multimedia fields, graphic and web designers who use 3D and animation, and professionals in engineering and scientific fields. Render a 3D image and merge it into a 2D composite image. Edit videos easily

What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? Mar 21, 2024 pm 04:16 PM

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

Tutorial on how to turn off the payment sound on WeChat Tutorial on how to turn off the payment sound on WeChat Mar 26, 2024 am 08:30 AM

1. First open WeChat. 2. Click [+] in the upper right corner. 3. Click the QR code to collect payment. 4. Click the three small dots in the upper right corner. 5. Click to close the voice reminder for payment arrival.

Experts teach you! The Correct Way to Cut Long Pictures on Huawei Mobile Phones Experts teach you! The Correct Way to Cut Long Pictures on Huawei Mobile Phones Mar 22, 2024 pm 12:21 PM

With the continuous development of smart phones, the functions of mobile phones have become more and more powerful, among which the function of taking long pictures has become one of the important functions used by many users in daily life. Long screenshots can help users save a long web page, conversation record or picture at one time for easy viewing and sharing. Among many mobile phone brands, Huawei mobile phones are also one of the brands highly respected by users, and their function of cropping long pictures is also highly praised. This article will introduce you to the correct method of taking long pictures on Huawei mobile phones, as well as some expert tips to help you make better use of Huawei mobile phones.

See all articles