02、手把手教Vue--指令

本節(jié)大綱

PS:轉(zhuǎn)載請注明出處
作者: TigerChain
地址: http://www.itdecent.cn/p/8a7ccaeda33f
本文出自 TigerChain 簡書 手把手教 Vue 系列

教程簡介

正文

一、Vue 的實例

通過上節(jié)課,我們知道如何引入 Vue 來工作,初學(xué)者不建議使用 vue-cli 來創(chuàng)建項目,在這里我們使用引入 script 來編寫 Vue demo

Vue 完全可以看做是面向?qū)ο蟮恼Z言,我們創(chuàng)建一個 Vue 的實例一般是這樣做的

var vm = new Vue({
  // 數(shù)據(jù)
  data:{
  },
  methods:{
    // 方法
  },
  等等其它 
})

我們可以看到 -- data 作為屬性、methods 作為方法,new Vue 就是一個實例對象,這樣理解 Vue 就會很輕松「如果有面向?qū)ο蟮幕A(chǔ)」

二、什么是指令

傳統(tǒng)意義上的指令就是指揮機器工作的指示和命令,vue 中的指令一般是以 v- 開頭

vue 中的指令的職責(zé)是,當(dāng)表達式的值改變時,會響應(yīng)式的對 DOM 產(chǎn)生影響

在開始指令之前,我們先來一個 helloWorld 來直觀的感受下下 Vue 吧

1、先來一個 HelloWorld

在這里我使用 atom 來開發(fā)

1、新建一個目錄,并且導(dǎo)入 vue.js 如下

基本目錄

2、打開 index.html,輸入以下內(nèi)容

<h3>Vue 的指令</h3>
<hr style="height:2px;border:none;border-top:2px dashed #0066CC;"  />
<ol>
   <li><a href="./instructions/hello.html">Hello World</a></li>
</ol>

以上是核心代碼,body 中的代碼「沒有寫 html 標(biāo)準(zhǔn)模版代碼,完整的可以看 index.html界面」

3、在 js 目錄下引入 vue.js 文件「在官方上下載」

添加 vue.js

4、在 instructions 目錄下新建 hello.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Vue--hello world</title>
  <script src="../js/vue.js"></script>
</head>
<body>
  <div id="container">{{msg}}</div>

  <script>
    var vm = new Vue({
      el:'#container',
      data:{
        msg:'hello world'
      }
    })
  </script>
</body>
</html>

5、查看一下結(jié)果吧,這里我們使用 browser-sync 來啟動一個服務(wù)「幫你解決手動刷新的困擾,看過我 react 系列的應(yīng)該非常熟悉」,這里不過多介紹 browser-sync , 了解更多請查看官網(wǎng):http://www.browsersync.cn

打開命令行,在根目錄下輸入

vue-study/vue-lesson/01、基本指令 // 在當(dāng)前目錄
 browser-sync start --server --files "**/*.css, **/*.html"
查看結(jié)果

就會自動打開默認瀏覽器,然后界面就出來了,往后你修改的內(nèi)容,不用 F5 不用刷新,內(nèi)容自動就同步了「真 TM 帥」

運行查看結(jié)果

看到了吧,輸入命令以后就會自動打開瀏覽器容器,并且顯示 index.html 的內(nèi)容,我們也正確的看到了 hello world 的內(nèi)容「使用 vue 創(chuàng)建的」

二、v-on,v-if,v-for 指令

1、v-on 是用來監(jiān)管 DOM 事件的,并執(zhí)行一些 js 代碼,比如點擊事件,提交事件等

用法

v-on:click="表達式"

廢話不多說直接上例子吧

  • 1、在 instructions 下新建 v-on.html,然后在 index.html 中引入

先看 index.html 中修改「見下面紅色框」

index.html 中添加 v-on.html
  • 2、v-on.html 給出 body 中的核心代碼「html 基本模版和 vue.js 引信省略」
<body>
  <div id="container">
    <!--這里添加 v-on:click 然后定義一個方法-->
    <input type="button" value="點我" v-on:click="clickme()"/>
    <p>{{num}}</p>
  </div>

  <script>
    var vm = new Vue({
      el:"#container",
      data:{
        // 定義一個數(shù)據(jù)默認是1
        num:1
      },
      // 方法寫在 methods 關(guān)建字中,從字名看里面可以多個方法
      methods:{
         // 這里就是 v-onclick:后面跟的方法
        clickme:function(){
          // this 指的是當(dāng)前對象 -- vm
          this.num++
        }
      }
    })
  </script>
</body>
  • 3、這樣一個簡單的 v-on:click 指令就可以使用了,我們來看一下結(jié)果
v-on 結(jié)果

PS: v-on 的縮寫

<!-- 完整語法 -->
<a v-on:click="doSomething">...</a>

<!-- 縮寫 -->
<a @click="doSomething">...</a>

2、v-if 和 v-for 指令

v-if 是條件判斷,v-for 是用來循環(huán)數(shù)據(jù)的,從名字就可以看出來

v-if 的模版

<div v-if="type === 'A'">
  A
</div>
<div v-else-if="type === 'B'">
  B
</div>
<div v-else-if="type === 'C'">
  C
</div>
<div v-else>
  Not A/B/C
</div>

其中 v-else-if 和 v-else 不是必須的「根據(jù)實際情況看是否需要」

v-for 的模版

<標(biāo)簽 v-for="item in mites">
    {{item}}
</標(biāo)簽>

比如:遍歷 li  假設(shè)有一個數(shù)組 items=[{"message":"hello"},"message":"vue"]
<ul id="container">
  <li v-for="item in items">
    {{ item.message }}
  </li>
</ul>

如果想要使用 v-for 來遍歷帶索引使用

v-for="(item,index) in items"

其中 index 就是索引,如果想使用索引的話就可以使用此種方式

這里的標(biāo)簽指的需要循環(huán)的標(biāo)簽,好了不多說了,直接看例子吧,下面我們實現(xiàn)一個下面的例子

v-if 和 v-for 指令

我們使用 v-if 來判斷需要顯示方形按鈕/div 還是圓形按鈕/div ,并且使用 v-for 遍歷了兩個數(shù)組「分別使用 ul 和 table 樣式顯示」

核心代碼

<div id="container">
      <h3>1、使用 v-if 來切換按鈕上的文字和 div 的顯示樣式</h3>
      <button v-on:click="cheangeDiv()" style="width:100px;">{{theWord}}</button>
      <!--  如果 flag 為 true 的話那么就顯示 div -->
      <div v-if="flag" >
        <div id="showDiv">
            我顯示出來了
        </div>
      </div>
      <!-- 否則顯示圓形的 div -->
      <div v-else>
        <div id="showBuleDiv"><span style="color:white">哈哈</span></div>
      </div>
   <hr>
   <h3>2、使用 v-for 來循環(huán)數(shù)組</h3>

    <span>列舉出你喜歡吃的水果</span><br/>
    我喜歡吃的水果有
    <ul>
      <li v-for="item in fruit">
        <span>{{item}}</span>
      </li>
    </ul>

  <h3> 3、使用 v-for 循環(huán)輸出 以下 json 串</h3>
  <p>
    mydatas:[
      {"name":"TigerChain","age":"保密","address":"地球中國","lover":"不告訴你"},
      {"name":"張三","age":"23","address":"地球中國","lover":"打游戲"},
      {"name":"李四","age":"25","address":"地球中國","lover":"讀書"},
      {"name":"王五","age":"30","address":"是中唯一不下雪的地方","lover":"寫代碼"},
      {"name":"趙六","age":"18","address":"中國北京","lover":"寫博客"},
      {"name":"錢七","age":"27","address":"中國陜西","lover":"做菜"}
    ]
  </p>
    <table border="1">
      <tr>
        <th>序號</th>
        <th>姓名</th>
        <th>年齡</th>
        <th>地址</th>
        <th>愛好</th>
      </tr>
      <tr v-for="(item,index) in mydatas">
        <!-- 其中 index 是索引,也就是數(shù)組的角標(biāo) -->
        <td><span>{{index}}</span></td>
        <td><span>{{item.name}}</span></td>
        <td><span>{{item.age}}</span></td>
        <td><span>{{item.address}}</span></td>
        <td><span>{{item.lover}}</span></td>
      </tr>
    </table>
  </div>

  <script>
    var vm = new Vue({
      el:'#container',
      // 數(shù)據(jù)
      data:{
        theWord:"圓形",
        flag:false,
        msg:'show me',
        mydatas:[
          {"name":"TigerChain","age":"保密","address":"地球中國","lover":"不告訴你"},
          {"name":"張三","age":"23","address":"地球中國","lover":"打游戲"},
          {"name":"李四","age":"25","address":"地球中國","lover":"讀書"},
          {"name":"王五","age":"30","address":"是中唯一不下雪的地方","lover":"寫代碼"},
          {"name":"趙六","age":"18","address":"中國北京","lover":"寫博客"},
          {"name":"錢七","age":"27","address":"中國陜西","lover":"做菜"}
        ],
        fruit:["蘋果","香蕉","葡萄","美國香瓜"]

      },
      // 方法
      methods:{
        // 切換 div
        cheangeDiv(){
          this.flag = !this.flag;
          if(this.theWord =="圓形"){
            this.theWord = "方形"
          }else{
            this.theWord = "圓形"
          }
        }
      }
    })
  </script>

具體代碼可以查看 https://github.com/tigerchain/vue-lesson 中的基本指令章節(jié)

3、v-show 和 v-model

v-show

在前面我們使用了 v-if 指令,v-show 的指令和 v-if 類似,基本模版是:

<標(biāo)簽 v-show="條件">如果達到條件要顯示的內(nèi)容</標(biāo)簽>

比如:我們有一個按鈕點擊顯示或隱藏 div 如下效果

v-show 效果

核心代碼:

<div id="container">
  <button @click="clickMe()">{{defaultButton}}</button>
  <!-- 如果 v-show = true 的話就會顯示 此 div  -->
  <div v-show="flag" id="showDiv">
    <span>我是 v-show</span>
  </div>
</div>

<script>
  var vm = new Vue({
    el:'#container',
    data:{
      // 是否顯示 div 的標(biāo)志,默認是不顯示
      flag:false,
      // 默認按鈕顯示字樣
      defaultButton:'顯示'
    },
    methods:{
      // 按鈕點擊的方法
      clickMe(){
        if(this.defaultButton == "顯示"){
          this.defaultButton ="隱藏"
        }else{
          this.defaultButton ="顯示"
        }
        this.flag = !this.flag
      }
    }
  })
</script>

從上面的例子中,我們可以感受到 v-show 的用法了

v-model

v-modle 體現(xiàn)了 mvvm 設(shè)計思想,它是一個雙向數(shù)據(jù)綁定「在 input 和 textarea 上」

我們直接在上面 id 為 container 的 div 中添加如下代碼

<input type="text" v-model="itext" class="myinput"> <br/>
你輸入的值是:<font class="myfont">{{itext}}</font>

并且我們在 data 中定義一個 itext 屬性

data:{
  // 是否顯示 div 的標(biāo)志,默認是不顯示
  flag:false,
  // 默認按鈕顯示字樣
  defaultButton:'顯示',
  // 新添加的屬性
  itext: ''
},

運行查看結(jié)果:

v-model結(jié)果

從上面的結(jié)果中我們可以看到,當(dāng)我們給 input 中輸入文本的時候就下面就會自動的顯示出所對應(yīng)的文本,并且點擊按鈕的時候改變文本的值,輸入框中的值會自動改變,這就是雙向綁定

三、來個 blog 實例

1、經(jīng)過上面我們學(xué)習(xí)了幾個指令,我們來寫一個綜合的小案例,效果如下:

v-blog

2、開始擼碼「在這里我們給出核心代碼」,后面會放出 demo 地址

我們在 instructions 目錄下新建一個 blog-demo.html 文件

  • 1、首先我們在這里要引入一個 sweetalert2.js 來做彈出框
  • 2、我們來看看 div 中的內(nèi)容
  <div id="container">
    <p>標(biāo)題:<input type="text" v-model="title" placeholder="標(biāo)題" ></p>
    <p>內(nèi)容:<textarea name="content" id="" cols="30" rows="10" v-model="content"></textarea></p>
    <p><input type="submit" value="添加" v-on:click="add" ></p>

    <hr>

    <table border="1">
      <tr>
        <th>序號</th>
        <th>標(biāo)題</th>
        <th>內(nèi)容</th>
        <th>操作</th>
      </tr>
      <!-- 遍歷把內(nèi)容顯示出來 -->
      <tr v-for="(data,index) in datas">
        <td>{{index+1}}</td>
        <td>{{data.title}}</td>
        <td>{{data.content}}</td>
        <td>
          <a href="#" v-on:click="deleteRow(index)">刪除</a>
          <a href="#" v-on:click="modifyData(index)">修改</a>
        </td>
      </tr>
    </table>
    <span v-show="datas.length!=0" ><a href="#" v-on:click="deleteAllData()">全部刪除</a></span>
    <!-- 沒有數(shù)據(jù)的顯示這個標(biāo)簽 -->
    <span v-show="datas.length==0">沒有數(shù)據(jù)</span>
  </div>

以上我們定義了一個 blog 的模版,下面我們給它添加一些操作功能

  • 3、添加 script 代碼

從上面的代碼中,我們看到了 v-modle,v-show ,v-for 等指令,下面我們來看看 vue 中的代碼

<script>
var vm = new Vue({
  el:'#container',
  data:{
    // 標(biāo)題
    title:'',
    // 內(nèi)容
    content:'',
    // 所有的內(nèi)容
    datas:[]
  },
  methods:{
    // 添加數(shù)據(jù)
    add(){
      if(this.title =="" || this.content==""){
        alert("標(biāo)題或內(nèi)容不能為空")
        return
      }
      // 把標(biāo)題和內(nèi)容添加到數(shù)組中
      this.datas.push({"title":this.title,"content":this.content})
      // 添加完數(shù)據(jù)以后把標(biāo)題和內(nèi)容置空
      this.title=""
      this.content=""
    },
    // 刪除數(shù)據(jù)
    deleteRow(index){
      //在一個方法中調(diào)用
      let that = this // 由于是在方法的方法內(nèi)部,this 就指的是當(dāng)前方法了, 所以要使用 var that = this 來聲明一下
     //在一個方法中調(diào)用 另一個方法
     this.$options.methods.deleteMethod(function callback(){
         that.datas.splice(index,1)
     })
    },
    //修改數(shù)據(jù)
    modifyData(index){
      // 取得原來的數(shù)據(jù)
      let data = this.datas[index]

      swal({
        title: '修改',
        // type: 'info',
        html:
          "<div><p>標(biāo)題:<input id=\"title\" value="+data.title+" ></input></p>"+
          " <p>內(nèi)容:<input  id=\"content\" value="+data.content+"></input></p></div>" ,

        showCancelButton: true,
        focusConfirm: false,
        confirmButtonText:'確定',
        cancelButtonText:'取消'
      }).then((result)=>{
        if(result.value){
          let title = document.getElementById('title').value
          let content = document.getElementById('content').value
          // 修改數(shù)據(jù)
          this.datas.splice(index,1,{"title":title,"content":content})
        }
      })
    },
    //刪除 全部數(shù)據(jù)
    deleteAllData(){
      //這里使用箭頭函數(shù)就不用再使用 let that = this 來轉(zhuǎn)化了,可以上面的比較一下,兩種方式
     this.$options.methods.deleteMethod(()=>{
       this.datas = []
     })
    },
    // 封裝一個刪除方法
    deleteMethod(callback){
      swal({
        title: '確定刪除嗎?',
        text: "全部刪除了以后就不恢復(fù)不了哦!",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        cancelButtonText:'取消',
        confirmButtonText: '確定刪除!'
      }).then((result) => {
        if (result.value) {
           callback()
        }
      })
    }
  }
})
</script>

以上就是 blog-demo 的核心代碼,注釋的非常清楚,這里不過多解釋了,請自行實踐

到此為止,我們就把 vue 的幾個常用的指令說完了

四、總結(jié)

通過這節(jié),我們學(xué)習(xí)了 vue 的幾個常見的指令,并且寫了一個小 demo ,通過動手就能直觀的感受到 vue 指令的作用

點贊是一種美德,轉(zhuǎn)發(fā)富五代

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容