Vue基礎(一)

基礎知識

基礎環境

  • vscode
  • 所需的插件:

jshint:JS代碼檢查
Beautify:代碼美化(選中代碼-->format doc)
Vetur: Vue插件
JavaScript (ES6) code snippets: ES6語法
Auto Rename Tag: 自動重命名標籤
Vue-helper:Vue提示
vscode-icons: 文件夾圖標
open in browser

vscode快捷鍵

ctrl+k以及ctrl+s打開快捷鍵窗口,以便查看快捷鍵

Vue 介紹

是一套構建前後端分離的架構

Vue的安裝和使用

三種方式:

  • script標籤引用
<!-- development version, includes helpful console warnings -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- production version, optimized for size and speed -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
  • npm安裝
  • vue-cli安裝

Vue體驗

<!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">
  <script src="../lib/vue.js"></script>
  <title>01VueStudy</title>
</head>

<body>
  <div id="app">
    <p>{{ greet() }}</p>
    <p>{{ username }}</p>
    <button @click="username='隔壁老王'">更改值</button>
  </div>
</body>
<script>
  new Vue({
    el: '#app',
    data: {
      username: "Hello"
    },
    methods: {
      greet() {
        return "你好啊"
      }
    }
  })
</script>

</html>

Vue的模板語法

  • v-bind: 屬性綁定
  • v-once: 在模板中只讀取一次變量,後續變量更改了,不會跟着變化
  • v-html: 解析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">
  <script src="../lib/vue.js"></script>
  <title>vue v-bind</title>
</head>
<body>
  <div id="app">
    <p v-once>{{ username }}</p>
    <p v-html='code'>{{ code }}</p>
    <button @click="username='隔壁老王'">改變</button>
    <img v-bind:src="logo" alt="">
  </div>
  
</body>
  <script>
    new Vue({
      el: "#app",
      data: {
        username: "Alex",
        code: "<a href='https://www.baidu.com'>BAT</a>",
        logo: "https://vuejs.org/images/logo.png"
      }
    })
  </script>
</html>

Vscode添加自定義代碼片段

  1. ctrl+shift+p
  2. 搜索Snippets關鍵字,選擇Preferance
  3. 選擇html.json,修改成如下的樣子
{
 "my vue html code": {
  "prefix": "html",
  "body": [
   "<!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'>",
   "    <script src='../lib/vue.js'></script>",
   "    <title>$1</title>",
   "</head>",
   "<body>",
   "    <div id='app'>",

   "    </div>",
   "</body>",
   "    <script>",
   "    new Vue({",
   "    el: '#app',",
   "    data: {",
   " $2",
   " }",
   "    })",
   "    </script>",
   "</html>",
  ],
  "description": "my vue html code"
 }
}

屬性綁定

  • 綁定class的兩種形式
<!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'>
  <script src='../lib/vue.js'></script>
  <title></title>
  <style>
    .title{
      font-size: 20px;
      color: red
    }
    .main-title{
      font-weight: 1800;
    }

  </style>
</head>
<body>
  <div id='app'>
    <!-- 數組方式 -->
    <p v-bind:class="[pclass1,pclass2]">I like Vue</p>
    <!-- 對象方式 -->
    <p :class="{'title':true,'main-title':strong}">我是隔壁老王</p>
    <button @click="strong=true">文字加粗</button>
    <!-- 對象方式 -->
    <p :style="{backgroundColor:backgroundColor}">屬性綁定樣例</p>
    <!-- 數組方式 -->
    <p :style="[Pstyle1,Pstyle2]">屬性綁定樣例2</p>
  </div>
</body>
  <script>
    new Vue({
      el: '#app',
      data: {
       pclass1: "title",
       pclass2: "main-title",
       strong: false,
       backgroundColor: "red",
       Pstyle1: {
         'background-color':'blue',
         'font-size': '30px'
       },
       Pstyle2: {
         "border-bottom":"2px solid #000"
       }
     }
    })
  </script>
</html>

使用JS表達式

在屬性綁定和變量讀取中,可以使用表達式。常見的表達式有: 變量讀取,變量運算,三目運算符,函數調用,取反等

<!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'>
  <script src='../lib/vue.js'></script>
  <title></title>
</head>
<body>
  <div id='app'>
    <div :style="{color: danger?'red':'black'}">{{ message.split(" ").reverse().join(" ") }}</div>
    <div>{{ greet() }}</div>
    <div>{{ !is_adult }}</div>
  </div>
</body>
  <script>
    new Vue({
      el: '#app',
      data: {
        // 條件?條件成立的值:條件不成立的值
      // danger: true
      danger: false,
      message: "Hello World Hello China",
      is_adult: true
      },
      methods: {
        greet() {
          return "Good Morning!!"
        }
      }

    })
  </script>
</html>

條件判斷

if系列

<!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'>
  <script src='../lib/vue.js'></script>
  <title>Vue 判斷</title>
</head>
<body>
  <div id='app'>
    <p v-if="weather=='sun'">GoPark</p>
    <p v-else-if="weather='rain'">WatchMovie</p>
    <p v-else>StayHome</p>
  </div>
</body>
  <script>
    new Vue({
      el: '#app',
      data: {
       weather: "rain"
     }
    })
  </script>
</html>

多重條件使用template

<!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'>
  <script src='../lib/vue.js'></script>
  <title>IF</title>
</head>
<body>
  <div id='app'>
    <template v-if="age < 18">
      <p>AAA</p>
    </template>
    <template v-else-if="age >=18 && age <= 20">
      <p>BBB</p>
    </template>

    <template v-else>
      <p>CCC</p>
    </template>   
  </div>
</body>
  <script>
    new Vue({
      el: '#app',
      data: {
       age: 24
     }
    })
  </script>
</html>

method小例子

<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <script src='../lib/vue.js'></script>
  <title>V-if</title>
</head>
<body>
  <div id='app'>
    <template v-if="loginType=='username'">
      <label>用戶名</label>
      <input type="text" name="username" placeholder="用戶名">
    </template>

    <template v-else-if="loginType=='email'">
      <label>郵箱</label>
      <input type="text" name="email" placeholder="email">
    </template>
    <button @click="changeLoginType">更換登錄類型</button>
    
  </div>
</body>
  <script>
    new Vue({
      el: '#app',
      data: {
        loginType: "username"      
     },
     methods: {
       changeLoginType() {
         //三目運算符
         this.loginType = this.loginType =='username'?"email":"username"
       }
     }
    })
  </script>
</html>

小結:

  1. v-if,v-else-if,v-else
  2. 如果想要某個調間下渲染多個元素,那麼就要使用template標籤
  3. Vue默認會重用相同的標籤來提高性能,如果不要重用的話,那就在對應的元素上加一個key屬性即可

v-show和v-if的區別

v-show: 是通過簡單的切換display來渲染信息,會一次性加載所有的元素,在頻繁切換的狀態下推薦使用,不能在template標籤上使用
v-if: 真正的條件渲染,如果條件更改了,會重新加載

<!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'>
  <script src='../lib/vue.js'></script>
  <title></title>
</head>
<body>
  <div id='app'>
    <div v-show="loginType=='username'">
      <label>用戶名</label>
      <input type="text" name="username" placeholder="username" key="username">
    </div>

    <div v-show="loginType=='email'">
      <label>郵箱</label>
      <input type="text" name="email" placeholder="email" key="email">
    </div>

    <button @click='changeLoginType'>切換登錄方式</button>

  </div>
</body>
  <script>
    new Vue({
      el: '#app',
      data: {
        loginType: "username"
     },
     methods: {
       changeLoginType() {
         this.loginType = this.loginType=='username'?'email':'username'
       }
     }
    })
  </script>
</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'>
  <script src='../lib/vue.js'></script>
  <title>loop</title>
</head>
<body>
  <div id='app'>
     <table>
       <thead>
         <tr>
           <th>Index</th>
            <th>bookName</th>
            <th>Author</th>
         </tr>
       </thead>
       <tbody>
         <tr v-for="book,index in books">
           <td>{{index+1}}</td>
           <td>{{ book.title }}</td>
           <td>{{book.author}}</td>
         </tr>
       </tbody>
     </table>
  </div>
</body>
  <script>
    new Vue({
      el: '#app',
      data: {
        books: [
          {
          'title':'Book1',
          'author':'1'
          },
          {
            'title': 'book2',
            'author': '2'
          },
          {
            'title':'book3',
            'author':'3'
          },
          {
            'title': 'book4',
            'author': '4'
          }
        ]
       
     }
    })
  </script>
</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'>
  <script src='../lib/vue.js'></script>
  <title>vue for</title>
</head>
<body>
  <div id='app'>
    <div v-for="(value,key) in person">
      {{ key }} : {{ value }}
    </div>
  </div>
</body>
  <script>
    new Vue({
      el: '#app',
      data: {
        person: {
          username: "alex",
          age: 18,
          homepage: "http://www.baidu.com"
        }       
     }
    })
  </script>
</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'>
  <script src='../lib/vue.js'></script>
  <title>vue-for</title>
</head>
<body>
  <div id='app'>
    <div v-for="book in books" :key="book.title">
      <label>標題:</label>
      <input type="text" :placeholder="book.title">
    </div>
    <button @click="changeBookSort">更改圖書順序</button>
  </div>
</body>
  <script>
    new Vue({
      el: '#app',
      data: {
        books: [
          {
          'title':'Book1',
          'author':'1'
          },
          {
            'title': 'book2',
            'author': '2'
          },
          {
            'title':'book3',
            'author':'3'
          },
          {
            'title': 'book4',
            'author': '4'
          }
        ]       
     },
     methods: {
       changeBookSort() {
         this.books.sort(function (a,b) {
           return Math.random(0,1) - 0.5
         })
       }
     }
    })
  </script>
</html>

小結:

  • 默認情況下,如果數組中的順序發生變化,或者個數比發生變化導致重新渲染,那麼vue就會重新利用之前的元素,而不會重新排序,這樣需要添加key屬性,key只能支持number和string類型
  • 在vue2.2+ ,key是必須的

視圖更新

針對數組中使用函數進行更新,有一下的方法直接觸發更新
push/pop/sort/splice/concat/reverse/shift/unshift

<!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'>
  <script src='../lib/vue.js'></script>
  <title>View Update</title>
</head>
<body>
  <div id='app'>
    <ul>
      <li v-for="role in roles" :key="role">
        {{role}}
      </li>
    </ul>
    <button @click="update">更新</button>
    <button @click="update2">更新2</button>
    <button @click="popRole">刪除最後一個元素</button>
    <button @click='shiftRole'>刪除第一個元素</button>
    <button @click='unshiftRole'>在第一個位置添加元素</button>
    <button @click='spliceTwo'>刪除前兩個元素</button>
    <button @click="spliceChange">替換前三個元素中的aaa爲XXXX</button>
    <button @click="spliceAdd">在第一個之前添加元素</button>
    <button @click=concatRole>合併數組</button>
  </div>
</body>
  <script>
    new Vue({
      el: '#app',
      data: {
        roles: ['aaa','bbb','ccc']       
     },
     methods: {
       // 直接賦值更新
       //通過函數更新
       update() {
         this.roles = ['ddd']
       },
       update2() {
         this.roles.push("eee")
       },
       popRole() {
         this.roles.pop()
       },
       shiftRole() {
         this.roles.shift()
       },
       unshiftRole() {
         this.roles.unshift("AAA")
       },
       spliceTwo() {
         this.roles.splice(0,2)
       },
       spliceChange() {
         this.roles.splice(0,4,'aaa','XXXX')
       },
       spliceAdd() {
         this.roles.splice(0,0,"dsadsadsa")
       },
       concatRole() {
        this.roles = this.roles.concat(['ssss','assfa'])
       }
     }
    })
  </script>
</html>

視圖更新
如果想要通過下標來更新數組中的某個值,這樣是不會觸發視圖更新的,需要通過Vue.set來實現

<!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'>
  <script src='../lib/vue.js'></script>
  <title>updateArray</title>
</head>
<body>
  <div id='app'>
    <ul>
        <li v-for="role in roles" :key="role">
            {{role}}
         </li>
    </ul>
    <div v-for="(value,key) in users">
      {{key}}:{{value}}
    </div>
    <button @click='updateArray'>更新Array</button>
    <button @click='updateObj'>更新對象</button>
  </div>
</body>
  <script>
    new Vue({
      el: '#app',
      data: {
       roles:["aa","bb","cc"],
       users: {"username":"BBB"}
     },
     methods: {
       updateArray() {
        // this.roles[0] = "dsadsadsd" 不能更新
        Vue.set(this.roles,0,'dadsffdafa')
       },
       updateObj() {
         this.users.username = "asdsfasfof",
         Vue.set(this.users,'age',19)
       }
     }
    })
  </script>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章