Expressions in templates are very convenient, but they are designed for simple calculations. Putting too much logic in templates can make them heavy and difficult to maintain. For example
<div id="example">
{
{message.split('').reverse() .join('')}}
</div>
In this place, templates are no longer simple declarative logic. You have to look at it for a while to realize that here is the flipped string that wants to display the variable message. When you want to include more of the flipped string here in the template, it will be more difficult to deal with, so for any complex logic, you should use computed properties.
Example usage:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="../js/vue.js"></script>
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title></title>
</head>
<body>
<div id="root">
{
{msgToUpper}}
</div>
<script>
new Vue({
el: '#root',
data: {
msg: "test"
},
computed: {
msgToUpper() {
return this.msg.toUpperCase();
}
}
})
</script>
</body>
</html>
Computed properties are read-only by default. When you try to modify a computed property, you will receive a runtime warning. You may only need to use "writable" properties in certain special cases, which you can create by providing both a getter and a setter:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="../js/vue.js"></script>
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title></title>
</head>
<body>
<div id="root">
<input type="text" v-model="msgToUpper">
{
{msgToUpper}}
</div>
<script>
new Vue({
el: '#root',
data: {
msg: "test"
},
computed: {
msgToUpper: {
get: function () {
console.log("getter..")
return this.msg.toUpperCase();
},
set: function (value) {
console.log("setter..")
this.msg = value
}
}
}
})
</script>
</body>
</html>