Computed and Listening Properties in vue

  • 2021-09-12 00:16:06
  • OfStack

Calculate attributes

Computed attributes are used to deal with complex business logic

Calculated attributes have dependencies. Calculated attributes depend on the initial value in data. Calculated attributes will only be evaluated again when the initial value changes

Calculated attribute 1 is written as a function and returns a value that has a dependency and will be recalculated only if the dependent value changes


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title> Form input binding </title>
</head>
<body>
 <div id="app">

  {{ reverseMsg }}---- {{ reverseMsg }}-------- {{ reverseMsg }} // Functions that directly use computed properties are the data you want 

 </div>
</body>
<script src="vue.js"></script> //vue Adj. js Or you won't be able to use it vue Grammar 
<script>
 const app = new Vue({
  el: '#app',
  data: {
   msg: 'hello world'
  },
  computed: {
   reverseMsg () { //  The computed attribute is 1 Functions that return 1 Values, using and data Options in 1 Sample 
    console.log('computed') //  Execute 1 Times  ---  Dependence 
    return this.msg.split('').reverse().join('');
   }
  }
 })
</script>
</html>

Listening properties (listening properties)

vue provides one attribute for detecting data changes. watch can obtain the changed value through newVal


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title> Form input binding </title>
</head>
<body>
 <div id="app">
  <input type="text" v-model="firstname"> + <input type="text" v-model="lastname"> = {{ fullname }}

 </div>
</body>
<script src="vue.js"></script>
<script>
 const app = new Vue({
  el: '#app',
  data: {
   firstname: ' Li ',
   lastname: ' Little dragon ',
   fullname: ' Bruce Lee '
  },
  watch: { //  Listening attribute 
   firstname (newVal, oldVal) { // newVal Value after change 
    this.fullname = newVal + this.lastname //  When change   Last name   Execute when 
   },
   lastname (newVal, oldVal) {
    this.fullname = this.firstname + newVal //  When change   Name   Execute when 
   }
  }
 })
</script>
</html>

The above is the vue compute attributes and listen to the details of the attributes, more about vue compute attributes and listen to the information please pay attention to the site of other related articles!


Related articles: