前端隨心記---------vuejs基礎學習3.0

watch ch 和cpmpute的區別:javascript

1.watch 表示監聽某個模型變量的狀態變化。watch監視的東西多一些,computed所依賴的東西都寫在一個函數裏。css

2.特殊場景:若是業務出現了異步操做(回調函數)則這個時候computed是存在返回值,不能在使用,可是watch裏面的沒有返回值的概念,能夠進行異步代碼的調用。html

小案例代碼:vue

<script type="text/javascript">
    var vm = new Vue({
        el: '#box',
        data: {
            username: '',
            msg: '',
        },
        // computed 完成信息的校驗 同步校驗,在本地作一些合法性的校驗; 最關鍵檢驗用戶名是否重複
        // 異步操做 ajax請求 校驗用戶名是否合法
        watch: {
            username: function () {
                // 檢測用戶名
                if( !this.username ) {
                    this.msg = '';
                    return; // 只是爲了終止代碼執行
                }

                if( this.username.length < 3 ){
                    this.msg = '* 用戶名的長度不能小於3個';
                    return; // 只是爲了終止代碼執行
                }

                if( this.username.length > 10 ){
                    this.msg = '用戶名的長度不能大於 10個';
                    return; // 只是爲了終止代碼執行
                }
                // 發送ajax請求進行操做
                var _That = this; // 方式一
                $.ajax({
                    url: './check.json',
                    type: 'GET',
                    dataType: 'json',
                    // 方式二: 使用箭頭函數 es5習慣
                    success: (json) => {

                        console.log(json);

                        if( !json['status'] ){

                            console.log(this); // ajax對象

                            this.msg = '用戶名已經被註冊,不能在使用了';
                        }
                        // return json['status']; // 是否能夠return出去

                    }
                });
                return '信息合法';
            }
        }

    })
</script>

在案例中,若是使用computed,沒法獲取ajax驗證以後的狀態,在異步ajax中沒法return 狀態。從而使用watch。java

 

watch的深度監控:jquery

 watch: {
            //  改爲了一個對象,屬性值 handler 固定寫法
            lists: {
                handler: function (newVal, oldVal) {
                    console.log('lists change....')
                },
                deep: true,
                // 表明開啓深度監控。意思數據的任何一個屬性發生變化,監視函數須要執行
                immediate: true,
                // 若是immediate 設置爲true, 表明代碼一加載 立馬執行監視函數。

            }
        }

 

小案例:

http://todomvc.com/

<!DOCTYPE html>
<html lang="zh_CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--1. 引入 bootstrap-->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">

    <script src="https://cdn.bootcss.com/jquery/2.0.1/jquery.js"></script>

    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.js"></script>

    <style>
        .del{
            text-decoration: line-through;
            color: #ccc;
        }
    </style>


</head>

<body>
<nav class="navbar navbar-inverse">
    <div class="container-fluid">
        <div class="navbar-header">
            <a class="navbar-brand" href="#">
                VUEJS_TODO
            </a>
        </div>
    </div>
</nav>

<div class="container" id="app">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-success">
                <div class="panel-heading">
                    <h3>-_-, 還有 {{onData}} 件事未完成</h3>
                    <input type="text" class="form-control" v-model="title" @change="addItem">
                </div>
                <div class="panel-body">
                    <ul class="list-group">
                        <li   @dblclick="editItem(todo)"
                              style="cursor:pointer;"
                              class="list-group-item"
                              :class="{del: todo.isComplice}"
                              v-for="todo in newData"

                        >



                            <div v-show="curItem !== todo">
                                <input type="checkbox"

                                       v-model="todo.isComplice"> {{ todo.title }}
                                <button type="button"
                                        @click="removeItem(todo)"
                                        class="btn btn-danger btn-xs pull-right">&times;
                                </button>
                            </div>


                            <input type="text"
                                   @blur="cancel"
                                   @change.13="cancel"

                                   v-show="curItem === todo"

                                   class="form-control"
                                   v-model="todo.title"

                                   v-focus="curItem === todo"

                            >

                        </li>
                    </ul>


                </div>
                <div class="panel-footer">
                    <ul class="nav nav-pills">
                        <li :class="{active:hash==='all'}"><a href="#/all">所有</a></li>
                        <li :class="{active:hash==='finish'}"><a href="#/finish">已完成</a></li>
                        <li :class="{active:hash==='unfinish'}"><a href="#/unfinish">未完成</a></li>
                    </ul>

                </div>
            </div>
        </div>
    </div>
</div>

</body>
<!--2. vuejs-->
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
<script>
  new Vue({
      el:'#app',
      directives: {
          focus: function (el, bindings) {
              if (bindings.value) {
                  el.focus();
              }
          }
      },
      data:{
          curItem:'',
          hash:'',
          title:'',
          isComplice:'',
          title:'',
          todos:[
      {
          title:'吃飯',
          isComplice:true,
      },
      {
          title:'吃飯',
          isComplice:false,
      },
      {
          title:'吃飯',
          isComplice:false,
      }
  ]},

      methods:{
          addItem:function () {
              this.todos.push({title:this.title,isComplice:false});
              this.title='';
          },
          removeItem:function (eles) {
              this.todos = this.todos.filter(function (ele) {
                  return ele !== eles;
              })
          },

          editItem:function (elee) {
              this.curItem=elee;
          },
          cancel: function () {
        this.curItem = '';// 清空當前項
         }
          
          
      },
        computed:{
          onData:function () {
            return  this.newData.filter(function (ele) {
                  return  !ele.isComplice;
              }).length;
          },
            newData:function () {
                if(this.hash=='finish'){
                    return this.todos.filter(function (ele) {
                        return ele.isComplice;
                    })
                }
                if(this.hash=='unfinish'){
                    return this.todos.filter(function (ele) {
                        return !ele.isComplice;
                    })
                }
                return  this.todos;

            }

        },

      watch:{
          todos:{
              handler:function (newVal,oldVal) {
                localStorage.setItem('toDoData',JSON.stringify(this.todos));
              },
              deep:true,
          },
      },
      created:function () {
          this.todos=JSON.parse(localStorage.getItem('toDoData'))||this.todos;
          window.addEventListener('hashchange', ()=> {
             this.hash= location.hash.slice(2);
          },false);
      },

  })


</script>
</html>
相關文章
相關標籤/搜索