In Vue.js, computed properties are properties that are calculated based on the values of other properties. They are useful when you want to perform some logic or calculations on your data and have the result available as a reactive property. Computed properties are cached and only re-evaluated when their dependencies change.
Create a variable or data property:
Here username
is a variable.
data() {
return {
"username": "michale jon"
}
}
Maybe you need to use your username
in upper or lower case. In that situation, computed properties are the best option to perform the necessary operation and show it in HTML.
Create computed property:
Syntax:
computed: { //define function custom_function_name() { return value; } }
computed: {
custom_username() {
return this.username.toUpperCase()
}
}
Use of custom function:
<h1>[[ custom_username ]]</h1>
Output:
MICHALE JON
Full Code:
{% extends "base.html" %}
{% load static %}
{% block content %}
<style>
#vue_app {
margin: 1rem;
}
</style>
<div id="vue_app">
<h1>[[ custom_username ]]</h1>
</div>
<script src="https://unpkg.com/vue@3"></script>
<script>
let app = Vue.createApp({
delimiters: ["[[", "]]"],
data() {
return {
"username": "michale jon"
}
},
computed: {
custom_username() {
return this.username.toUpperCase()
}
}
})
app.mount('#vue_app')
</script>
{% endblock content %}