vue:利用computed搭配watch監測data物件值之變化

by cactus77kiki

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<div id="app">
  【name監測中...請查看console】
  <br/>
  <div>
    <input type="text" v-model='single.id'>
    <input type="text" v-model='single.name'>
    <input type="text" v-model='single.mobile'>
  </div>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

JavaScript

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Play around in JSFiddle", done: true },
      { text: "Build something awesome", done: true }
    ],
    single:{ id: 1, name:'ptt', mobile: '0912-345678',stype:'a'},
    addmode: true,
    querymode: false,
    editmode: false,
    spaceC: true
  },
  computed: {
        // I just want to watch title for now
        title: function() {
            return this.single.name;
        }
    },
  watch: {
  	title :function(n, o){
    	if(n!=o)
      	console.log('value has changed');
      console.log(n);
      console.log(o);
    }
  },
  methods: {
  	toggle: function(todo){
    	todo.done = !todo.done
    }
  }
})

/*
vue watch
origin:https://github.com/vuejs/vue/issues/2164
ref: http://jsfiddle.net/54emch61/
*/