vue (computed property)

Basic structure of computed properties

computed property

 You can write some attributes of calculation logic in it.

 He does not directly return the result like ordinary functions, but returns the result after a series of calculations.

 At the same time, as long as a certain attribute in data is applied to it, when this attribute changes, the calculated attribute can sniff this change and execute it automatically

 Definition: The attribute to be used does not exist, and it is calculated from the existing attributes.

Use: Define the calculated property in the computed object, and use { {method name}} to display the calculated result  on the page .

Cache properties for computed properties

 When the computed property is called for the first time, a result will be generated, and the result will be cached, and each subsequent use of this property will be taken from the cache.

 When its dependencies change, it will recalculate to get a result, and then cache it

<script>
    //基本结构
    new Vue ({
        el:'',
        //数据

        data:{},
        // 方法属性
        // 事件绑定,不用return,没有缓存

        methods:{},
        // 侦听器(重视结构)
        // 监听一个值的改变,不用返回值
        watch:{
                要侦听的数据(){}
        },
        // 计算属性(重视结果)
        // 必须有return,只求结果,有缓存
        copputed:{
            计算属性名(){
                //经过一系列计算
                return 处理操作后结果
            }

        }
    })
 </script>

Basic use of computed properties

<div id="app">

        <p>Original string: { { message }}</p>

        <p>Calculate the reversed string: { {·reverseMessage·}}</p>

        <p>Convert the original string to lowercase: { { toLowerCase}}</p >

        </div>

       

        <script src="../vue.js"></script>

        <script>

        new View({

        the:'#app',

         data:{

        message:'ABCDEFG'

         },

        computed:{

        // Compute the reversed string

        reverseMessage:function(){

        // split() splits a string into an array of strings

        // reverse() reverses the order of the elements in the array

        // join() converts all elements in the array to a string

        return this.message.split('').reverse().join('')

    },

    //Convert the original string to lowercase

    toLowerCase(){

        //substring(from,to) extracts characters between two specified subscripts in the string

        //toLowerCase() is used to convert a string to a trumpet

        return this.message.substring(0,7).toLowerCase

    }

}

        })

        </script>

The full structure of computed properties

 1. Each computed property contains a getter function and a setter function.

    2. The computed property will use the getter function by default, and the setter function is not common, so the general computed property getter and setter are not written.

    3. The getter function is the default usage, but the setter function is not the default usage. If you want to use a setter function, you must manually write out the setter function.

    4. The formal parameter in the setter function is the value you want to modify

<!-- 准备好一个容器 -->
<div id="app">
姓:<input type="text" v-model="lastName"> <br><br>
名:<input type="text" v-model="firstName"> <br><br>
全名:<span>{
   
   { fullNamel}</span> <br><br>
<button @click="btn">修改计算属性的值</button>
</div>
<!-- 引入Vue -->
<script src="../vue.js"></script>

<script>
new Vue({
el:'#app',
 data(){
return {
firstName:'图图', 
lastName:'胡'
}
},
computed:{
fullName:{
// get:获取值时触发
// 当有人读取ful1Name时,get就会被调用,且返回值就作为fullName的值。
 get(){
return this.firstName +'_' +this.lastName;
},
//set;设置值时触发
//当计算属性被修改时,调用set
set(value){
    console.log('set',value);
    const arr = value.split('-')
    this.firstName = arr[0]
    this.lastName = arr[1]
}
}
},
methods:{
    btn(){
        this.fullName = '胡英俊'
    }
}
})
</script>

                                                         2

<script>

        // 1. Declaration string

let str = 'The Center of the Universe - Jiangxi Software Vocational and Technical University';

let str1 = "The center of the universe - Jiangxi Software Vocational and Technical University";

let str10 = 'The center of the universe - Jiangxi Software Vocational and Technical University';

// 2. Determine whether a string is in a string

let index1 = str.index0f('universe')

console.log(index1);//0

// 3. Intercept the string (the first parameter: which subscript to start intercepting; the second parameter: the length of the interception.

 let str2 = str.substr(7,2)

 console.log(str2); // Jiangxi

// 4. Modify the string (the first parameter: the string to be modified; the second parameter: the modified string.

let str3 = str.replace("Universe","Internet")

console.log(str3);// The center of the Internet--Jiangxi Software Vocational and Technical University

// 5. Split the string

let str4 = "23"

// This function must return an array

let array = str4.split(',')

// is the delimiter, when the delimiter is found, it is removed from the string and an array of substrings is returned.

// If the delimiter is not found or omitted, the array contains one element consisting of the entire string.

// If the delimiter is an empty string, convert str to a character array

console.log(array); //['Scatter', "Lang'," Hey', 'Yo']

// 6. Case conversion (only English has case, Chinese does not exist)

console.log('ABCDEF'.toLowerCase());// convert to lowercase abcdef

console.log('abcdef'.toUpperCase());// convert to uppercase ABCDEF

console.log('Case does not exist in Chinese'.toLowerCase);

    </script>

Operation

<body>
    <script src="./vue.js"></script>
    <style>
        div#app {
        width:250px;
        margin: 30px auto;
        border: 1px solid □#666;
         border-radius:10px; 
         padding:10px;
        }
        
        p {
            text-align: center;
        }
       
        </style>
        </head>
        <body>
        <div id="app">
        <p>
        <input type="text" placeholder="猜数字"v-model="gueassed">
    </p >
    <p>
        {
   
   {res}}</p >
        </div>
        <script>
        new Vue({
        el: '#app', data:{
        gueassed:'',
        // 生成随机数0-100
        a:Math.floor(Math.random() * 100),},
        computed:{
        res:{
        //当有人读取fantcc,就会调用get, 
        get() {
        const b = this.gueassed * 1; 
        const a = this.a
        if (a == b)
        return"恭喜你猜对了"
         if (b == 0)
        return "请猜一个介于1和100之间的整数";
         if (b > a)
        return"大了,往大一点猜"
         if (b < a)
        return"小了,往大一点猜"
        },
        }	}	
        })
        </script>
</body>

 

Guess you like

Origin blog.csdn.net/m0_73495603/article/details/127324336