Table of Contents
What is a computed property
Use computed properties to implement data filtering
Use computed properties to implement sorting and filtering
Home Web Front-end Vue.js Data visualization function application examples in Vue documents

Data visualization function application examples in Vue documents

Jun 20, 2023 pm 04:46 PM
vue data visualization Function application

Vue.js is a popular JavaScript framework for building interactive web user interfaces. It provides a flexible data binding system and easy way to compose and reuse components.

In the Vue.js documentation, data visualization usage in JavaScript is called computed properties. In this article, we will introduce some computed properties in Vue.js and show how to leverage them to create real-world applications that use data visualization.

What is a computed property

A computed property is a special function in Vue.js that is used to calculate and return dynamic data binding values ​​based on responsive dependencies. They automatically update the results based on the properties defined in the Vue.js instance. This means that when the dependent property changes, the calculated property will automatically recalculate its value. The syntax of the calculated property is as follows:

computed: {
  // 计算属性的名称
  属性名: function() {
    // 计算属性的计算逻辑
    return 计算结果
  }
}
Copy after login

In the above syntax, the calculated property is defined by property name, and its value is a function that returns the calculation result.

For example, assume we have the following Vue.js instance:

new Vue({
  el: '#app',
  data: {
    firstName: 'John',
    lastName: 'Doe'
  },
  computed: {
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }
})
Copy after login

In this example, we define the computed property fullName, whose returned value is The combination of firstName and lastName.

Use computed properties to implement data filtering

Using computed properties, we can more easily implement data filtering based on specific conditions. For example, assume we have the following Vue.js instance:

new Vue({
  el: '#app',
  data: {
    todos: [
      { text: '任务 1', done: true },
      { text: '任务 2', done: false },
      { text: '任务 3', done: false }
    ],
    filter: 'all'
  },
  computed: {
    filteredTodos: function () {
      if (this.filter === 'all') {
        return this.todos
      } else if (this.filter === 'done') {
        return this.todos.filter(function (todo) {
          return todo.done
        })
      } else if (this.filter === 'undone') {
        return this.todos.filter(function (todo) {
          return !todo.done
        })
      }
    }
  }
})
Copy after login

In this example, we define a state variable named filter, which can take one of the following three values : all, done, and undone. We also define a calculated property named filteredTodos, which calculates and returns our filtered task array based on different filter conditions.

Now, we only need to bind the buttons pointing to different filter conditions to the filter property to complete the task filtering. For example:

<button @click="filter = 'all'">全部</button>
<button @click="filter = 'done'">已完成</button>
<button @click="filter = 'undone'">未完成</button>
<ul>
  <li v-for="todo in filteredTodos">
    {{ todo.text }}
  </li>
</ul>
Copy after login

In this example, we use the v-for directive to render each task in filteredTodos into HTML. When we click a filter condition button, filter will be assigned the corresponding filter condition, and the calculated attribute will recalculate and update the task list.

Use computed properties to implement sorting and filtering

In addition to filtering, we can also use computed properties to sort data according to actual needs. For example, let's say we have the following Vue.js instance:

new Vue({
  el: '#app',
  data: {
    items: [
      { name: 'A', price: 6.5 },
      { name: 'B', price: 2 },
      { name: 'C', price: 5 },
      { name: 'D', price: 4.2 },
      { name: 'E', price: 8 },
    ],
    sortKey: 'name',
    sortReverse: false,
    filterKey: ''
  },
  computed: {
    sortedItems: function () {
      var key = this.sortKey
      var reverse = this.sortReverse ? -1 : 1

      var items = this.items.slice().sort(function (a, b) {
        a = a[key]
        b = b[key]
        return reverse * ((a > b) - (b > a))
      })

      if (this.filterKey) {
        items = items.filter(function (item) {
          return (
            item.name.toLowerCase().indexOf(this.filterKey.toLowerCase()) !== -1 ||
            item.price.toString().indexOf(this.filterKey) !== -1
          )
        }.bind(this))
      }

      return items
    }
  }
})
Copy after login

In this case, we define a state variable named items, and each item has a state variable named ## Properties of #name and price. At the same time, we also define three states: sortKey, sortReverse and filterKey.

We also define a calculated property called

sortedItems, which automatically calculates and sorts the items array based on sorting and filtering conditions. We can automatically switch between sorting and descending order by clicking on the table header, and filter the array by entering text.

<table>
  <thead>
    <tr>
      <th>
        <button @click="sortKey = 'name'; sortReverse = !sortReverse">
          商品名称
        </button>
      </th>
      <th>
        <button @click="sortKey = 'price'; sortReverse = !sortReverse">
          商品价格
        </button>
      </th>
    </tr>
    <tr>
      <th>
        <input v-model="filterKey" placeholder="商品名称或价格" />
      </th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="item in sortedItems">
      <td>{{ item.name }}</td>
      <td>{{ item.price }}</td>
    </tr>
  </tbody>
</table>
Copy after login
In this example, we used the

v-model directive to implement a filter entered by the user. We also used two buttons to toggle the sorting criteria.

Conclusion

By using computed properties, we can easily build Vue.js applications with data visualization. Computed properties interact with Vue.js’ reactive system, thus making our data filters and sorters more flexible and easier to use.

When we are building applications with data visualization, computed properties are an excellent way to implement data manipulation and view rendering. The examples above demonstrate some basic and advanced features of computed properties to help you get started using them in your Vue.js applications.

The above is the detailed content of Data visualization function application examples in Vue documents. 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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1240
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

See all articles