Vue study notes (14) - computed properties

Computed property:

  1. Definition: The element to be used does not exist, it must be calculated from existing attributes

  1. Principle: The bottom layer uses the getter and setter provided by the Object.defineproperty method

  1. When is the get function executed?

  1. Executed once when first read

  1. Called again when dependent data changes

  1. Advantages: Compared with the implementation of methods, there is an internal cache mechanism (multiplexing), which is more efficient and convenient for testing

  1. Remark:

  1. If the attribute will eventually appear on the vm, just read and use it directly

  1. If the calculated attribute needs to be modified, then the set function must be written to respond to the modification, and the set will cause the data that the calculation depends on to change

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>姓名案例-计算属性语法实现</title>
    <!-- 引入Vue -->
    <script type="text/javascript" src="../js/vue.js"></script>
  
</head>
<body>
<!-- 准备一个容器 -->
<div id="root">
  姓:<input type="text" v-model="na"><br><br>
  名:<input type="text" v-model="me"><br><br>
  <!-- 虽然多次使用了name,但是只调用了一次get,那是因为首次调用就存在了缓存中,
  后面直接从缓存里读取就可以,直至数据改变时 -->
  全名:<span>{
    
    {name}}</span><br><br>
  全名:<span>{
    
    {name}}</span><br><br>
  全名:<span>{
    
    {name}}</span><br><br>
  全名:<span>{
    
    {name}}</span>
</div>
 
<script type="text/javascript">
Vue.config.productionTip=false
Vue.config.keyCodes.huiche=13//定义了一个别名键
const vm=new Vue({
    el:'#root',
    data:{
        na:'张',
        me:'三'
    },
  
   computed:{// 存放计算属性,计算属性不能放在data里面
    name:{
        //get什么时候调用?1.初次读取name时.2.所依赖的数据发生改变时
        get()
        {
            return this.na+ '-'+this.me
        },
        //修改时调用
        set(value){
            const arr=value.split('-')//按照指定字符,将数组拆分
            this.na=arr[0]
            this.me=arr[1]
            // name=value,因为是计算属性,这里就不需要写了,以经计算完了
        }
    }
   }
})
 
</script>
</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_54763080/article/details/128835027