Vue.js- Calculation Properties and class Binding to style

Learning notes:Front-end development document

Calculation attribute

All calculated attributes are written in Vue instances as functionscomputedOption, finally return the calculated results.

Usage of computed attributes

All kinds of complicated logic can be completed in a calculation attribute, including operations, function calls, etc., as long as a result is finally returned.

The calculation attribute can also depend on the data of multiple Vue instances. As long as any data changes, the calculation attribute will be re-executed and the view will be updated.

Each computed attribute contains agetterAnd onesetter.

In most cases, only the default will be usedgetterThe method reads a calculation attribute, which is rarely used in businesssetter, so when you declare a calculated attribute, you can use the default writing method directly. you do not need togetterAndsetterBoth declared.

Besides simple text interpolation, computational attributes are often used to dynamically set the style names of elements.classAnd inline stylesstyle. When using components, computed properties are also often used for dynamic passingprops.

There are also two practical tips for calculating attributes that are easily overlooked:

  1. First, the calculation attribute can depend on other calculation attributes;
  2. Second, the calculation attribute can not only depend on the data of the current Vue instance, but also on the data of other instances.
<div id="app1"></div>
    <div id="app2">
    {{reverseText}}
</div>

var app1 = new Vue({
    el: "#app1",
    data: {
        text: '123,456'
    },
});
var app2 = new Vue({
    el: "#app2",
    computed: {
        reverseText: function () {
            //这里依赖的是实例app1的数据text
            return app1.text.split(',').reverse().join(',');
        }
    }
});

Calculate attribute cache

No calculation attribute is used, inmethodsA method is defined in to achieve the same effect. Even the method can accept parameters and is more flexible to use.

The reason for using a computed attribute is its dependency cache.. When the data on which a calculation attribute depends changes, it will re-take the value. In the above example, as long astextIf the value does not change, the calculation attribute will not be updated. butmethodsIt is different, as long as it is re-rendered, it will be called, so the function will also be executed.

Do you use calculated properties ormethodsDepending on whether you need caching or not, when traversing large arrays and doing a large number of calculations, you should use calculation properties unless you do not want caching.

V-bind and class bind with style

v-bindThe main use of is to dynamically update attributes on HTML elements.

In data binding,v-bindThe two most common applications are the style names of elementsclassAnd inline stylesstyleThe dynamic binding of.

BindingclassSeveral ways of

Object syntax

tov-bind:classSet an object that can be switched dynamicallyclass

<div id="app">
    <div :class="{'active':'isActive'}">测试文字</div>
</div>

new Vue({
    el: "#app",
    data: {
        isActive: true
    },
});

Objects can also be passed in multiple attributes to switch dynamicallyclass. In addition,:classCan be compared with ordinaryclassCoexistence.

<div class="static" :class="{'active':'isActive','error':isError}">测试文字</div>

data: {
    isActive: true,
    isError: false
}

When:classIf the expression of is too long or the logic is complex, you can also bind a calculation property. When there are more than two conditions, both can be useddataOrcomputed.

In addition to calculating attributes, you can also directly bind data of type Object, or use a that is similar to calculating attributes.methods.

Array syntax

When multiple applications are requiredclassYou can use array syntax to:classBind an array, apply anclassList:

<div id="app">
    <div :class="[activeCls,errorCls]">测试文字</div>
</div>

new Vue({
    el: "#app",
    data: {
        activeCls: 'active',
        errorCls: 'error'
    }
});

// 结果
<div class="active error">测试文字</div>

You can also use ternary expressions to switch according to conditionsclass

<div :class="[isActive ? activeCls : '',errorCls]">测试文字</div>

new Vue({
    el: "#app",
    data: {
        isActive: true,
        activeCls: 'active',
        errorCls: 'error'
    }
});

WhenclassWhen there are multiple conditions, you can use object syntax in array syntax:

<div id="app">
    <div :class="[{'active':isActive},errorCls]">测试文字</div>
</div>

Using computation attributes to dynamically set class names for elements is often used in business, especially when writing reusable components, so in the development process,If the expression is long or the logic is complex, the evaluation attribute should be used as preferentially as possible..

Used in Components

If used directly on custom componentsclassOr:class, style rules are applied directly to the root element of this component.

Vue.component('my-component', {
    template: `<p class="article">一些文本</p>`
});

Then when this component is called, the object syntax or array syntax is applied to bind the component.class

<div id="app">
    <my-component :class="{'active':isActive}"></my-component>
</div>

This usage is only applicable to custom components where the outermost layer is a root element, otherwise it will be invalid. When this condition is not met or a class name needs to be set for a specific child element, the of the component should be usedpropsTo deliver.

Binding inline style

Use:styleYou can bind inline styles, methods, and:classSimilarly, there are also object syntax and array syntax, much like writing CSS directly on elements.

<div id="app">
    <div :style="{'color':color, 'fontSize':fontSize+'px'}">文本</div>
</div>

new Vue({
    el: "#app",
    data: {
        color: 'red',
        fontSize: 14
    }
});

The style is usually written indataOrcomputedMedium:

<div id="app">
    <div :style="styles">文本</div>
</div>

new Vue({
    el: "#app",
    data: {
        styles: {
            color: 'red',
            fontSize: 16 + 'px'
        }
    }
});

In actual business,:styleThe array syntax of is not commonly used and can be written in an object, while the more commonly used is to calculate attributes.

In addition, use:styleVue.js will automatically prefix special CSS attribute names, such astransform.