vue學習

聰明絕頂的你與即將禿頭的我發表於2020-10-03

Vue文件:https://cn.vuejs.org

Vue簡介

vue是一套用於構建使用者介面的漸進式框架,Vue 被設計為可以自底向上逐層應用。Vue 的核心庫只關注檢視層,不僅易於上手,還便於與第三方庫或既有專案整合。另一方面,當與現代化的工具鏈以及各種支援類庫結合使用時,Vue 也完全能夠為複雜的單頁應用提供驅動。

Vue的引入

1.開發環境版本(適合學習階段的編碼使用)

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

2.生產環境版本(速度較快,程式碼壓縮)

<script src="https://cdn.jsdelivr.net/npm/vue"></script>

宣告式渲染

Vue.js的核心是一個允許採用簡潔的模板語法來宣告式地將資料渲染進DOM的系統:

<div id="app">
  {{ message }}
</div>
var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
})

el掛載點:el命中的元素內部用{{}}修飾的部分被data中同名的資料給替換,把message替換為Hello Vue!

vue例項的作用範圍是什麼?

答:el選項命中的元素及其內部的後代元素

 

是否可以用其他的選擇器?

答:可以,但是建議選id選擇器,因為id唯一,其他選擇器會命中多個元素,會造成語義的不清晰

 

是否可以設定其他的dom元素? 

答:可以。但是隻能支援雙標籤。還有一些特殊的比如<body></body>、<html></html>不可以。建議用div作為掛載的元素,因為div沒有什麼額外的樣式。

 

data:資料物件(vue中的資料定義在data中,data可以寫複雜型別的資料,渲染複雜型別資料遵循js語法就行)

<body>

   <div id="app">

       {{ message }}

     <h2> {{ student.name}} </h2>

      <ul>

         <li>{{ hometown[0] }}</li>

      </ul>

  </div>

 <script>

   var app=new Vue({

   el:"#app",

   data:{

     message:"hello world",

    student:{

       name:"lkq",

       age:20

     },

     hometown:["北京","新疆","天津"]

   });

  </script>

</body>

 

v-text

設定標籤的內容(textContent)

預設寫法會替換全部內容,使用插值表示式{{}}可以替換指定內容,內部支援寫表示式(字元拼接)

<body>

   <div id="app>
      <h2 v-text="message+'!'"></h2>
      <h2>hello{{ message +"!"}}</h2>
   </div>

   <script>

    var app=new Vue({
        el:"#app",
       data:{
          message:"hello"
        }
   })

   </script>

</body>

v-html

作用:設定元素的innerHtml,內容中有html結構會被解析為標籤,v-text無論內容是什麼,只會被解析為文字

如果有Html結構而且需要渲染就用v-html,如果只是文字就用v-text

<body>

    <div id="app">

         <p></p>

    </div>

    <script>

       var app=new Vue({

          el:"#app",

          data:{

             content:"<a href='#'>hello world</a>"

           }

        })

     </script>

</body>

v-on

作用:為元素繫結事件

注意:事件名不需要寫on,指令可以簡寫為@,繫結的方法定義在methods屬性中

<body>

    <div id="app">

        <input type="button" value="事件繫結" v-on:事件名="方法">//事件名:比如click、monseenter、dblclick

                                                                                                       //方法:dolt

        <input type="button" value="事件繫結"  @dblclick="dolt">//另一種寫法

      <h2 @click="changeFood">{{ food }}</h2>

  </div>

   <script>

        var app=new Vue({

           el:"app",

           data:{

              food:"蕃茄炒雞蛋"

             },

           methods:{

             dolt:function(){

               alert('你好');

             },

             changeFood:function(){

                 this.food='涼拌黃瓜'

             }

          }

        })

   </script>

</body>

案例——計數器

點選“-”數量減少,點選“+”,數量增加

<body>

   <div id="app">

    <div class="input-num">

       <button @click>-</button>

       <span>{{num}}</span>

       <button @click>+<button>

    </div>

    </div>

   <script>

      var app=new Vue({

     el:"#app",

     data:{

       num=0

     },

     methods:{

        add:function(){

           if(this.num>10)

             alert('超過10,不能增加');

           else

            this.num++;

        },

         sub:function(){

              if(this.num<1)

              alert('不能減少了');

              else

              this.num--;

         }

     }

    })

 </script>

</body>

v-show

作用:根據表示式的真假,切換元素的顯示和隱藏(比如廣告、遮罩層),原理是改變元素的display屬性,實現顯示和隱藏

注意:指令後面的內容,最後都會解析為布林值,true顯示,false隱藏,資料改變後,元素對應狀態對同步更新

<body>

    <div id="app">

       <img src="地址" v-show="isShow">

       <img src="地址" v-show="age>=18">

     </div>

     <script>

         var app=new Vue({

              el:"#app",

             data:{

               isShow:true,

               age:18

             }

         })

       </script>

</body>

案例:點選按鈕,顯示圖片,在點選,不顯示圖片

<body>

     <div id="app">

        <input type="button" value="切換 顯示狀態" @click="changeIsShow">

        <img v-show="isShow" src="./img/pink.gif" alt="">

     </div>

     <script>

           var app=new Vue({

             el:"#app",

             data:{

               isShow:false

              },

             methods:{

              changeIsShow:function(){

                this.isShow=!this.isShow;

              }

           }

        })

   </script>

</body>

v-if

作用:根據表達值的真假,切換元素的顯示和隱藏(操縱dom元素)

本質:通過操縱dom元素來切換顯示狀態。表示式為true,元素存在於dom數中,為false,從dom樹移除

<body>

    <div id="app">

       <p v-if="true">p1</p>

       <p v-if="isShow">p2</p>

    </div>

    <script>

        var app=new Vue({

          el:"#app",

          data:{

           isShow:false

          }

     })

   </script>

</body>

案例:同v-show

<body>

    <div  id="app">

         <input type="button" value="切換顯示" @click="toggleIsShow">

         <p v-if="isShow">hello</p>

   </div>

   <script>

       var app=new Vue({

           el:"#app",

          data:{

             isShow:false

          },

         methods:{

            toggleIsShow:function(){

              this.isShow=!this.isShow;

            }

         }

    })

   </script>

</body>

v-show和v-if的區別:

v-show操縱的是樣式,v-if操縱的是dom樹,工作中頻繁切換的元素用v-show,反之用v-if,因為操縱dom樹對效能消耗比較大

 

v-bind

作用:設定元素的屬性(比如src , title , class),寫法v-bind:屬性名=表示式,v-bind可以省略

<body>

     <div id="app">

         <img :src="imgSrc">

        <img :title="imgTitle+'!!!'">

        <img :class="isActive?'active':""">

        <img :class="{active:isActive}">//推薦寫法

      </div>

      <script>

             var app=new Vue({

                 el:"#app",

                data:{

                  imgSrc:"圖片地址",

                  imgTitle:"懸停文字",

                 isActive:false

                  }

           })

      </script>

</body>

案例:圖片切換

點選"<"切換到左圖片,點選">"切換到右圖片

切換圖片的本質是修改src屬性,隱藏"<"  ">"本質就是修改display屬性

通過陣列來儲存多個圖片地址,屬性用v-bind來,事件繫結用v-on,隱藏標籤用v-show

<body>

     <div id="app">

          <div id="center">

             <h2 class="title">

               <img src="./images/logo.png" alt="">

              標題

             </h2>

        <img :src="imgArr[index]" alt="">

       <a href="#" @click="prev" v-show:"index!=0">上一張</a>

       <a href="#" @click="next" v-show:"index<imgArr.length-1">下一張</a>

    </div>

    <script>

        var app=new Vue({

             el:"#app",

            data:{

            imgArr:["./images/00.jpg","./images/01.jpg";],

            index:0

           },

          methods:{

            prev:function(){

              if(this.index!=0)

               this.index--;

             },

           next:function(){

               if(this.index<this.imgArr.length)

               this.index++;

             }

     })

   </script>

</body>

 

v-for

作用:根據資料生成列表結構,響應式

<body>

    <div id="app">

        <ul>

              <li v-for="item in arr"></li>//遍歷陣列元素

              <li v-for="(item,index) in arr" :title:"item"> {{ item }}</li>//遍歷陣列元素及索引

              <li v-for="(item,index) in obj" > {{ item.name }}</li> //如果不是陣列,是複雜型別,比如物件

       </ul>

    </div>

    <script>

         var app=new Vue({

            el:"#app",

            data:{

              arr:[1,2,3,4,5]

            }

       })

    </script>

</body>

 

案例:

<body>

   <input type="button" value="新增資料" @click="add">

  <input type="button" value="刪除資料" @click="delete">

   <div id="app">

      <ul>

            <li v-for="item in arr">

               where are you from?{{ item }}

            </li>

      </ul>

      <h2 v-for="item in vegetables" :title="item.name">

           {{ item.name}}

       </h2>

   </div>

   <script>

        var app=new Vue({

           el:"#app",

           data:{

             arr:['北京','上海','杭州'],

             vegetables:[

                {name:'蕃茄炒雞蛋'},

                {name:'涼拌黃瓜'},

                {name:'小雞燉蘑菇'}

             ]

             },

            methods:{

                  add:function(){

                    this.vegetables.push({name:'新增'});

                    }

                   delete:function(){

                   this.vegetables.shift();

                  }

         })

    </script>

</body>

 

v-on的補充

傳遞自定義引數:事件繫結的方法寫成函式呼叫的形式,可以傳入自定義引數,定義方法時需要定義形參來接收傳入的實參

事件修飾符:事件後面跟上.修飾符,可以對事件進行限制

<body>

   <div id="app">

      <input type="button" @click="dolt(p1,p2)">

      <input type="text" @keyup.enter="sayHi">

   </div>

   <script>

       var app=new Vue({

           el:"#app",

           methods:{

             dolt:function(p1,p2){},

             sayHi:function(){}

           }

     })

   </script>

</body>

v-model

作用:獲取和設定表單元素的值(雙向資料繫結),繫結的資料會和表單元素的值相關聯,無論修改誰另一個都會同步更新

<body>

    <div id="app">

        <input type="text" v-model="message">

     </div>

    <script>

        var app=new Vue({

            el:"#app",

           data:{

               message:"hello"

            }

        })

    </script>

</body>

案例:記事本

文字框輸入值,回車後新增到頁面上,想刪除某條,滑鼠放上去,會出現“x”,點選“x”,刪除對應條目。左下角有個總數,右下角clear清空。

1.新增(1)生成列表結構v-for陣列  (2)獲取使用者輸入v-model (3)回車,新增資料v-on.enter

2.刪除(1)刪除指定內容 v-on splice 根據索引刪除對應元素

3.統計 (1)統計資訊個數,就是列表元素個數,即陣列長度 v-text length

4.清空 (1)清除所有資訊v-on 清空陣列

5.隱藏,底部的clear和統計在沒有任何元素時會被隱藏,v-if或v-show 陣列非空就顯示

<body>

    <section id="today">

         //輸入框

         <header class="header">

             <h1>記事本</h1>

            <input v-model="inputValue"  @keyup.enter="add" autofocus="autofocus" autocomplete="off" placeholder="請輸入任務" class="new-today">

          </header>

          //列表區

          <section class="main">

                <ul class="today-list">

                       <li class="today" v-for="(item,index) in list">

                           <div class="view">

                          <span class="index">{{ index+1 }}</span>

                          <label>{{ item }}</label>

                          <button class="destroy" @click="remove(index)"></button>

                         </div>

                       </li>

                   </ul>

              </section>

          //統計和清空

          <footer class="footer" v-if="list.length!=0">

               <span class="today-count">

                      <strong>{{ list.length }}</strong> item left

                </span>

               <button v-show="list.length!=0" class="clear-completed" @click="clear">

               Clear

               </button>

          </footer>

      </section>

        <script>

          var app=new Vue({

            el:"#today",

           data:{

              list:["吃飯","約會","看電影"],

              inputValue:"學習"

             },

             methods:{

                add:function(){

                        list.push(this.inputValue);

                 },

                remove:function(index){

                       this.list.splice(index,1);

                 },

                clear:function(){

                     this.list=[];

                }

            }

        })

        </script>

</body>

axios的基本使用

功能強大的網路請求庫

導包:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

axois.get(地址).then(function(response){},function(err){} )

地址就是文件提供的介面地址,第一個回撥函式會在請求響應完成的時候觸發,第二個會在請求失敗的時候觸發。

他們的形參可以用來獲取資訊,一個是伺服器響應的內容,一個是錯誤的資訊,如果需要傳遞引數,在url後面跟上查詢字串就行。

axois.get(地址?key=value&&key2=value2).then(function(response){},function(err){} )

key是文件提供的,value是我們具體要傳輸的資料

axois.post(地址,{key:value,key2:value2}).then(function(response){},function(err){})

案例:

介面1:隨機笑話

請求地址:https://autumnfish.cn/api/joke/list

請求方法:get

請求引數:num(笑話條數,數字)

響應內容:隨機笑話

<script>

       document.querySelector(".get").οnclick=function(){

           axios.get("https://autumnfish.cn/api/joke/list1234?num=3")

           .then(function(response){

               console.log(response);

           }),function(err){

               console.log(err);

           }

       }

</script>

介面2:使用者註冊

請求地址:https://autumnfish.cn/api/user/reg

請求方法:post

請求引數:username(使用者名稱,字串)

響應內容:註冊成功或失敗

<script>

document.querySelector(".post").οnclick=function(){

           axios.post("https://autumnfish.cn/api/user/reg",{username:"marry"})

           .then(function(response){

               console.log(response);

           },function(err){

               console.log(err);

           })

       }

</script>

axios+vue

案例:點選按鈕,隨機生成笑話,並渲染到頁面

<body>

    <div id="app">

    <input type="button" value="獲取笑話"  @click="getJoke">

    <p>{{ joke }}</p>

    </div>  

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <script>

       var app=new Vue({

           el:"#app",

           data:{

               joke:"這是個笑話"

           },

           methods:{

               getJoke:function(){

                 var that=this;

                 axios.get("https://autumnfish.cn/api/joke").then

                 (function(response){

                    console.log(response.data);

                    that.joke=response.data;

                 },function(err){

                     console.log(err);

                 })

               }

           }

       })

    </script>

</body>