vue範例 - deep watch(2種方式)

by cactus77kiki

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<div id="app">
  
  <br/>
  <div>
    <div style='background-color:lightblue;color:blue;'>#請於stype欄位輸入英文以check轉大寫效果</div><br/>
    {{single.id}} - 
    <input type="text" v-model='single.name' style='width:70px'>
    <input type="text" v-model='single.mobile' style='width:100px'>
    <input type="text" v-model='single.stype' style='width:100px'>
  </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:''},
    addmode: true,
    querymode: false,
    editmode: false,
    spaceC: true
  },
  computed: {
        // I just want to watch title for now
        title: function() {
            return this.single.name;
        }
    },
  watch: {
  	//deep watch(1)
  	title :function(n, o){
    	if(n!=o)
      	console.log('value has changed');
      console.log(n);
      console.log(o);
    },
    //deep watch(2)
    single: {
    	handler: function (val) {
				//轉大寫
        val.stype = val.stype.toUpperCase();
      },
      deep: true      
    }
  },
  methods: {
  	toggle: function(todo){
    	todo.done = !todo.done
    }
  }
})

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