watch和computed均可以监控程序员想要监控的对象,当这些对象发生改变之后,可以触发回调函数做一些逻辑处理
watch监控自身属性变化
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <input type="text" v-model="firstName" /> <input type="text" v-model="lastName" />
{{fullName}} </div> <script> new Vue({ el: ‘#app‘, data: { firstName: ‘hello‘, lastName: ‘vue‘, fullName: ‘hello.ve‘ }, watch: { ‘firstName‘: function(newval, oldval) { // console.log(newval,oldval); this.fullName = this.firstName + this.lastName; }, ‘lastName‘: function(newval, oldval) { // console.log(newval,oldval); this.fullName = this.firstName + this.lastName; } } }); </script> </body> </html>
watch监控路由对象
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script src="https://unpkg.com/[email protected]/dist/vue-router.js"></script> </head> <body> <div id="app"> <router-link to="/login">登录</router-link> <router-link to="/register/value">注册</router-link> <!--组件的显示占位域--> <router-view></router-view> </div> <script> //1.0 准备组件 var App = Vue.extend({}); var login = Vue.extend({ template: ‘<div><h3>登录</h3></div>‘ }); var register = Vue.extend({ template: ‘<div><h3>注册{{name}}</h3></div>‘, data: function() { return { name: ‘‘ } }, created: function() { this.name = this.$route.params.name; } }); //2.0 实例化路由规则对象 var router = new VueRouter({ routes: [{ path: ‘/login‘, component: login }, { path: ‘/register/:name‘, component: register }, { path: ‘/‘, //当路径为/时,重定向到/login redirect: ‘/login‘ } ] }); //3.0 开启路由对象 new Vue({ el: ‘#app‘, router: router, //开启路由对象 watch: { ‘$route‘: function(newroute, oldroute) { console.log(newroute, oldroute); //可以在这个函数中获取到当前的路由规则字符串是什么 //那么就可以针对一些特定的页面做一些特定的处理 } } }) </script> </body> </html>
计算属性computed的特点
- 计算属性会依赖于他使用的data中的属性,只要是依赖的属性值有改变,则自动重新调用一下计算属性;
- 如果他所依赖的这些属性值没有发生改变,那么计算属性的值是从缓存中来的,而不是重新编译,那么性能要高一些,所以vue中尽可能使用computed替代watch。
案例演示
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <input type="text" v-model="firstName" /> <input type="text" v-model="lastName" /> {{fullName}} </div> <script> new Vue({ el: ‘#app‘, data: { firstName: ‘hello‘, lastName: ‘vue‘ }, computed: { fullName: function() { return this.firstName + this.lastName; } } }); </script> </body> </html>