computed

作用:动态数据依赖(当前数据依赖另一个数据)

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>侦听器watch</title>
  8. </head>
  9. <body>
  10. <div id='app'>
  11. {{reverseMsg}}
  12. <h3>{{fullName}}</h3>
  13. <button @click='handleClick'>改变</button>
  14. </div>
  15. <script src="./vue.js"></script>
  16. <script>
  17. new Vue({
  18. el: '#app',
  19. data: {
  20. msg: 'hello world',
  21. firstName: 'ecithy',
  22. lastName: '哥'
  23. },
  24. methods: {
  25. handleClick(){
  26. this.msg = '计算属性computed';
  27. this.lastName = '妹';
  28. }
  29. },
  30. computed: {
  31. // computed默认只有getter方法
  32. // 计算属性最大的优点:产生缓存 如果数据没有发生变化 直接从缓存中取
  33. reverseMsg: function () {
  34. return this.msg.split('').reverse().join('')
  35. },
  36. fullName: function () {
  37. return this.firstName + this.lastName;
  38. }
  39. },
  40. })
  41. </script>
  42. </body>
  43. </html>

setter方法

输入的数据动态绑定给data

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>计算属性setter</title>
  8. </head>
  9. <body>
  10. <div id='app'>
  11. {{content}}
  12. <input type="text" v-model='content' @input = 'handleInput'>
  13. <button @click='handleClick'>获取</button>
  14. </div>
  15. <script src="./vue.js"></script>
  16. <script>
  17. new Vue({
  18. el: '#app',
  19. data: {
  20. msg: '',
  21. },
  22. methods: {
  23. handleInput:function(event){
  24. const {value} = event.target;
  25. this.content = value;
  26. },
  27. handleClick(){
  28. // console.log();
  29. if (this.content) {
  30. console.log(this.content);
  31. }
  32. }
  33. },
  34. computed: {
  35. content:{
  36. set:function(newV){
  37. this.msg = newV;
  38. },
  39. get:function(){
  40. return this.msg;
  41. }
  42. }
  43. },
  44. })
  45. </script>
  46. </body>
  47. </html>