vue3.x computed语法

 

注:实例环境 vue cli构建的项目

app.vue

<template>
  <Example></Example>
</template>

<script>
import Example from './components/Example'

export default {
  name: 'App',
  components: {
    Example
  }
}
</script>

<style>

</style>

Example.vue

<template>
    <div>
        <label>加法:</label>
        <input type="number" v-model="num1"/><span>+</span><input type="number" v-model="num2"/><span>=</span>{{total}}
        <hr>
        <table>
            <thead>
            <tr>
                <td>学科</td>
                <td>分数</td>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>语文</td>
                <td><input type="text" v-model.number="chinese"/> </td>
            </tr>
            <tr>
                <td>数学</td>
                <td><input type="text" v-model.number="math"/></td>
            </tr>
            <tr>
                <td>英语</td>
                <td><input type="text" v-model.number="english"/></td>
            </tr>
            <tr>
                <td>总分</td>
                <td>{{sum}}</td>
            </tr>
            <tr>
                <td>平均分</td>
                <td>{{average}}</td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
    export default {
        name: "Example",
        data:function () {
            return {
                num1:0,
                num2:0,
                newListText:'',
                username:'',
                age:0,
                chinese:97,
                math:90,
                english:98
            }
        },
        computed:{
            sum:function () {
                return parseFloat(this.chinese) + parseFloat(this.math) + parseFloat(this.english);
            },
            average:function () {
                return Math.round(this.sum / 3)
            },
            total:function () {
                return parseInt(this.num1) + parseInt(this.num2);
            }
        }
    }
</script>

<style scoped>

</style>

刷新浏览器

vue3.x computed语法


 
上一篇:v-for和v-if不能同时使用


下一篇:VUE高频面试题