[Front-end Development] One article will help you master the Vue.js framework (6)

Preface

In the previous article, we learned about conditional statements, loop statements and other knowledge points of vue.js. Now let us continue the study of the Vue series.

Property and style binding in Vue play an indispensable role in development. For example, implementing unit conversion, monitoring and responding to data changes and input events, etc. This article will explain the above knowledge points based on examples.

Insert image description here


Computed properties

Vue.js computed properties are a convenient, declarative way to define a property associated with template data binding. They can be used to process and transform data, and are only re-evaluated when the data they depend on changes.

The definition format of computed properties is:

computed: {
    
    
  // 计算属性名称
  propertyName: {
    
    
    // 计算函数/方法
    get () {
    
     /* 计算函数体 */ }
  }
}

Among them, propertyName is the name of the calculated property, and the get() method is the calculation function of the calculated property. It will automatically monitor data changes and recalculate when needed.

When using computed properties in templates, just access them like normal properties, such as:

<div>{
   
   { reversedMessage }}</div>

Here's a simple example showing how to define a computed property:

<div id="app">
  <p>{
   
   { message }}</p>
  <p>{
   
   { reversedMessage }}</p>
</div>
var app = new Vue({
    
    
  el: '#app',
  data: {
    
    
    message: 'Hello World'
  },
  computed: {
    
    
    reversedMessage: function() {
    
    
      return this.message.split('').reverse().join('')
    }
  }
})

In the above code, we define a calculated property namedreversedMessage. It splits the letters in the attribute using the split function, reverses them using the function, and finally uses The function re-concatenates them into a single string. messagereversejoin

Let’s take an example and try to reverse Quewuhua into Huawuque:

Insert image description here

As can be seen from the above figure, we successfully implemented the reversal of strings using calculated properties.

In Vue.js, computed properties are cached based on their dependencies. In other words, when the dependent data changes, it will be re-evaluated. In this way, when the calculated property is accessed multiple times, it does not need to be recalculated each time, but directly returns the previously cached value.


Listening properties

In addition to calculated properties, Vue.js also provides a similar instance methodwatch for monitoring and responding to changes in data.

Properties used to monitor and respond to data changes are called monitoring properties.

watchYou can monitor changes in one or more properties and perform corresponding operations after the changes occur.

Here is an example using thewatch method:

<div id = "app">
    <p style = "font-size:25px;">计数器: {
   
   { counter }}</p>
    <button @click = "counter++" style = "font-size:25px;">点我</button>
</div>
<script type = "text/javascript">
var vm = new Vue({
      
      
    el: '#app',
    data: {
      
      
        counter: 1
    }
});
vm.$watch('counter', function(nval, oval) {
      
      
    alert('计数器值的变化 :' + oval + ' 变为 ' + nval + '!');
});
</script>

In HTML, there is a container element with the id "app", which is used to mount Vue applications.

In the Vue instance, a data attribute named "counter" is defined with an initial value of 1.

Renders the value of the counter to a tag on the page using double curly brace interpolation syntax{ { counter }}. <p>

is bound to the button through the @click command. When the button is clicked, the counter value will increase by 1.

Usevm.$watch method to monitor changes in the "counter" attribute, and pop up a warning box to display the old and new values ​​of the counter every time it changes.

The response is as follows:

Insert image description here

We can also use watch to convert kilometers to meters:

<div id = "computed_props">
    千米 : <input type = "text" v-model = "kilometers">
     : <input type = "text" v-model = "meters">
</div>
<p id="info"></p>
<script type = "text/javascript">
    var vm = new Vue({
    
    
    el: '#computed_props',
    data: {
    
    
        kilometers : 0,
        meters:0
    },
    methods: {
    
    
    },
    computed :{
    
    
    },
    watch : {
    
    
        kilometers:function(val) {
    
    
            this.kilometers = val;
            this.meters = this.kilometers * 1000
        },
        meters : function (val) {
    
    
            this.kilometers = val/ 1000;
            this.meters = val;
        }
    }
    });
    // $watch 是一个实例方法
    vm.$watch('kilometers', function (newValue, oldValue) {
    
    
    // 这个回调将在 vm.kilometers 改变后调用
    document.getElementById ("info").innerHTML = "修改前值为: " + oldValue + ",修改后值为: " + newValue;
})
</script>

As you can see from the figure below, the use of listening attributes in Vue is very fast and efficient:

Insert image description here


style binding

Vue.js provides multiple ways to implement style binding. Here are several commonly used style binding methods:

1. Object syntax: Use object syntax to dynamically bind styles based on conditions. You can define a style object in data and then bind it to the element. For example, suppose there is a data attribute called isActive that indicates whether an element should be active. You can bind styles like this:

<div :class="{ active: isActive }"></div>

In the above example, if isActive is true, < will be added to the div element a i=4>class. active

2. Array syntax: Use array syntax to bind styles at the same time based on multiple conditions. You can define an array containing multiple class names in data and then bind it to the element. For example, suppose there is a data attribute named classNames, which is an array containing multiple class names. You can bind styles like this:

<div :class="classNames"></div>

In the above example, the class names in the classNames array will be added to the div element.

3. Bind inline style objects: We can also use object syntax to bind inline styles. You can define a style object in data and then bind it to the element's style attribute. For example, suppose you have a data property named customStyle, which is an object that contains multiple style properties. You can bind styles like this:

<div :style="customStyle"></div>

In the above example, the style attributes in the customStyle object will be applied to the inline styles of the div element.

for example:

<div id="app">
    <template>
      <div :style="{ color: textColor, fontSize: fontSize + 'px' }">绑定内联样式对象的实例</div>
    </template>
  </div>

  <script>
    new Vue({
      
      
      el: "#app",
      template: `![在这里插入图片描述](https://img-blog.csdnimg.cn/a59efc156f194dcd9139d8ff447660ce.png)

        <div :style="{ color: textColor, fontSize: fontSize + 'px' }">绑定内联样式对象的实例</div>
      `,
      data() {
      
      
        return {
      
      
          textColor: "blue",
          fontSize: 20
        };
      }
    });
  </script>

In this example, the text color of the div element will be set to blue (controlled by the textColor attribute) and the font size will be based on The value of the fontSize attribute is dynamically calculated.

Let’s take a look at the page’s echo:

Insert image description here

As you can see from the echo, we have completed style binding.


Summarize

The above isFront-end development: One article will help you master the Vue.js front-end framework series (6), leading readers to master calculated properties and monitoring properties and style binding.

The front-end development series will continue to be updated, and readers can subscribe to the column to continue learning.

Insert image description here

Guess you like

Origin blog.csdn.net/2301_77485708/article/details/133978246