vue初學篇----監視器(watch和computed)
阿新 • • 發佈:2018-11-19
監視器使用方法
<template> <div class="watchAndComputed"> <h1 v-text="watchAndComputedTitle"></h1> <input v-model="watchAndComputedText"/> <button @click="changeArrayLsit">改變實體資料</button> <span>新資料:{{watchNew}} 老資料:{{watchOld}}</span> <hr/> <input v-model="n1"/>+<input v-model="n2"/>*<input v-model="rate"/> = {{resultComputed}} </div> </template> <script> let vm ; export default { name: 'watchAndComputed', data() { vm = this; return { watchAndComputedTitle: 'vue監視用法', watchAndComputedText:'1', watchNew:'1', watchOld:'1', arrayList: [ { "code": "1", "value": "北京市" }, { "code": "2", "value": "上海市" }, { "code": "3", "value": "廣州市" }, { "code": "4", "value": "深圳市" }, { "code": "5", "value": "杭州市" }, { "code": "6", "value": "天津市" }, { "code": "7", "value": "西安市" }, { "code": "8", "value": "武漢市" }, { "code": "9", "value": "長沙市" } ], n1:'', n2:'', rate:'', } }, methods:{ changeArrayLsit:function(){ console.log(vm.arrayList); for(let b of vm.arrayList){ b.code +="code"; } } }, /* 單個的監聽 */ watch:{ arrayList: { deep: true, handler: function (newV, oldV) { vm.watchAndComputedText = Number(vm.watchAndComputedText)+1; console.log(newV, oldV); } }, watchAndComputedText:function(newV,oldV){ vm.watchNew = newV; vm.watchOld = oldV; } }, computed:{ resultComputed:function(){ return (Number(vm.n1)+Number(vm.n2))*Number(vm.rate); } } } </script>
監視器主要就是熟練的使用,在這裡展示出來一個例子,一個是文字框裡面的基本書記型別新老資料變化一個是複雜資料型別的變化,一個是監控多個的變化,具體結果如下圖所示: