十三、computed

  1. computed是依赖缓存进行计算的,只有所依赖的缓存发生改变才会重新计算。如果只没有发生改变,会直接取缓存里面的值
  2. 计算属性必须return一个值
  3. computed里的计算函数是可以直接当作data使用,不需要()
  4. 计算属性里面计算出来的值还可以拿来重新计算

<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>Documenttitle>
head>
<body>
  <div id="app">
    <label>
      <span>span>
      <input type="text" v-model="xing">
    label>
    <label>
      <span>span>
      <input type="text" v-model="ming">
    label>
    <label>
      <span>姓名span>
      <input type="text" v-model="name">
    label>
  div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
  <script>
    new Vue({
      el: '#app',
      data () {
        return {
          xing: '',
          ming: '',
        }
      },

      computed: {
        name() {
          return this.xing + this.ming
        }
      }
    })
  script>
body>
html>

computed的setter和getter

计算属性默认只有getter,但是也提供了setter

<body>
  <div id="app">
    <label>
      <span>span>
      <input type="text" v-model="xing">
    label>
    <label>
      <span>span>
      <input type="text" v-model="ming">
    label>
    <label>
      <span>姓名span>
      <input type="text" v-model="name">
    label>
  div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
  <script>
    new Vue({
      el: '#app',
      data () {
        return {
          xing: '',
          ming: '',
        }
      },

      computed: {
        name: {
          // getter
          get: function() {
            return this.xing + this.ming
          },
          // setter
          set: function(val) {
            this.xing = val.slice(0, 1)
            this.ming = val.slice(1)
          }
        }
      }
    })
  script>
body>

上面的代码通过get函数实现把姓输入框的值(xing)和名输入框的值(ming)相加起来,并把姓名绑定到姓名输入框(xingming)
set函数接收一个参数,就是姓名输入框输入的值,并把这个值进行分割分别赋值给xingming

你可能感兴趣的:(vue)