官术网_书友最值得收藏!

Computed properties

In this section, we'll be looking at computed properties within our Vue instance. This allows us to create small, declarative functions that return a singular value based on items inside of our data model. Why is this important? Well, if we kept all of our logic inside of our templates, both our team members and our future self would have to do more work to understand what our application does.

Therefore, we can use computed properties to vastly simplify our templates and create variables that we can reference instead of the logic itself. It goes further than an abstraction; computed properties are cached and will not be recalculated unless a dependency has changed.

Let's create a simple project to see this in action:

# Create a new Vue.js project
$ vue init webpack-simple computed

# Change directory
$ cd computed

# Install dependencies
$ npm install

# Run application
$ npm run dev

Interpolation is powerful; for example, inside of our Vue.js templates we can take a string (for example, firstName) and reverse this using the reverse() method:

<h1>{{  firstName.split('').reverse().join('') }}</h1>

We'll now be showing a reversed version of our firstName, so Paul would become luaP. The issue with this is that it's not very practical to keep logic inside of our templates. If we'd like to reverse multiple fields, we have to then add another split(), reverse(), and join() on each property. To make this more declarative, we can use computed properties.

Inside of App.vue, we can add a new computed object, that contains a function named reversedName; this takes our logic for reversing our string and allows us to abstract this into a function containing logic that would otherwise pollute the template:

<template>
<h1>Name: {{ reversedName }}</h1>
</template>

<script>
export default {
data() {
return {
firstName: 'Paul'
}
},
computed: {
reversedName() {
return this.firstName.split('').reverse().join('')
}
}
}
</script>

We could then see more information about our computed properties within Vue.js devtools:

Using devtools to display data

In our simple example, it's important to realize that, while we could make this a method, there are reasons why we should keep this as a computed property. Computed properties are cached and are not re-rendered unless their dependency changes, which is especially important if we have a larger data-driven application.

主站蜘蛛池模板: 长海县| 永新县| 绵阳市| 偏关县| 新疆| 崇义县| 綦江县| 汶上县| 公主岭市| 肥乡县| 贡山| 六盘水市| 涟水县| 青龙| 商洛市| 满洲里市| 原阳县| 怀安县| 临沭县| 乐东| 宁阳县| 临夏县| 襄城县| 崇信县| 乐陵市| 府谷县| 嵊州市| 礼泉县| 柏乡县| 固始县| 阳城县| 正安县| 措勤县| 达孜县| 永胜县| 正镶白旗| 长治县| 黄浦区| 长乐市| 陈巴尔虎旗| 衢州市|