VUE changes background color

1. Determine needs

Before implementation, we first need to clarify the requirement, that is, users can change the background color of the page in some way, so we need to provide an operable control to implement this function.

2. Create Vue components

In order to implement the page background color replacement function, we can create a Vue component. Here is a simple Vue component example:

 

<template>
  <div>
    <h1>当前背景颜色:{
   
   { backgroundColor }}</h1>
    <div>
      <button @click="setBackgroundColor('red')">红色</button>
      <button @click="setBackgroundColor('green')">绿色</button>
      <button @click="setBackgroundColor('blue')">蓝色</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      backgroundColor: 'white',
    };
  },
  methods: {
    setBackgroundColor(color) {
      this.backgroundColor = color;
      document.body.style.backgroundColor = color;
    },
  },
};
</script>

 In this example, we use a backgroundColorvariable to store the background color of the current page. When the user clicks the button, we setBackgroundColorchange the background color by calling a method and apply the background color to bodythe element at the same time.

3. Create a Vue instance

In order to display our Vue component, we need to create a Vue instance. Here's an example:

<template>
  <div>
    <h1>我的网站</h1>
    <background-control></background-control>
  </div>
</template>

<script>
import BackgroundControl from './BackgroundControl.vue';

export default {
  components: {
    'background-control': BackgroundControl,
  },
};
</script>

In this example, we BackgroundControladd the component we just created to the template and wrap it in a <div>. Then, we need to register the component with the Vue instance.

4. Add styles

Finally, we need to add styles to beautify our controls. Here is an example of styles:

button {
  padding: 10px;
  margin-right: 10px;
  border: none;
  border-radius: 5px;
  color: white;
  font-size: 16px;
}

button.red {
  background-color: red;
}

button.green {
  background-color: green;
}

button.blue {
  background-color: blue;
}

In this example, we use CSS styles to beautify our buttons. We set a standard style for each button, and then added different background color styles for redthe , greenand buttons respectively.blue

Guess you like

Origin blog.csdn.net/hulinhulin/article/details/133188480