【Vue使用学习Day5】watch和computed+webpack使用

筅森魡賤 提交于 2020-02-29 20:12:36

其实已经完全是Day6了嘛哈哈哈哈哈哈。
webpack的使用单独整理成笔记了,在这里

下面是关于Vue的watch和computed的,内容不多。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>watch和computed</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
    </head>
    <body>
        <div id="box">
            <input type="text" v-model="firstname"> +
            <input type="text" v-model="lastname"> =
            <input type="text" v-model="fullname">
            <hr>
            <input type="text" v-model="first"> +
            <input type="text" v-model="last"> =
            <input type="text" v-model="full">
        </div>
        <template id="com1"></template>
        <script>
            var box = new Vue({
                el: '#box',
                data: {
                    firstname: '',
                    lastname: '',
                    fullname: '',
                    first: '',
                    last: ''
                },
                methods: {},
                watch: {//watch监听data中指定数据的变化然后触发watch的处理函数
                    //watch里面的函数有两个参数newValue, oldValue,表示改变新旧数据
                    'firstname': function (newVal, oldValue) {
                        //this.fullname = this.firstname + '-' + this.lastname
                        this.fullname = newVal + '-' + this.lastname
                        console.log(newVal, oldValue)

                    },
                    'lastname': function (newVal) {
                        //this.fullname = this.firstname + '-' + this.lastname
                        this.fullname = this.firstname + '-' + newVal
                        //不过这个简单的场景通过@keyup也可以实现(但是就没有newval和oldval了
                    }
                    //也可以用watch监听路由改变
                    // '$route.path': function (newVal, oldVal) {}
                },
                computed: {
                    /*在computed中可以定义一些计算属性
                    计算属性的本质是一个方法,不过在使用的时候,
                    是把它们的名称,直接当作属性来使用而不是当作方法去调用*/
                    'full': function () {
                        //计算属性在引用时不能加小括号,当做普通属性用就OK
                        //计算属性函数里涉及到的data,一旦变化,会立马重新计算
                        //计算属性的结果会被缓存起来下次直接用
                        return  this.first + '---' + this.last
                    }
                }
            });
        </script>
    </body>
</html>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!