天天看點

Vue基礎文法 ->(個人學習記錄筆記)

@

目錄

  • Vue
    • 1. 指令
      • 1.1 mustache
      • 1.2 v-once
      • 1.3 v-html
      • 1.4 v-text
      • 1.5 v-pre
      • 1.6 v-cloak
      • 1.7 v-bind
        • 1.7.1 基本使用
        • 1.7.2 動态綁定class
          • 對象文法
          • 數組文法
          • 案例
        • 1.7.3 動态綁定style
          • 對象綁定
          • 數組綁定
      • 1.8 v-on
        • 1.8.1 基本使用
        • 1.8.2 參數問題
        • 1.8.3 修飾符
      • 1.9 v-if & v-else
        • 條件渲染案例
      • 1.10 v-show
      • 1.11 v-for
        • 周遊數組
        • 周遊對象
      • 1.12 v-model
        • 原理
        • 基本使用
        • v-model:radio
        • v-model:checkbox
        • v-model:select
        • 修飾符
    • -------------------------------
      • 2.計算屬性
        • 2.1 基本使用
        • 2.2 複雜操作
        • 2.3 setter和getter
        • 2.4 緩存
      • 3. ES6補充
        • 3.1 let/var
        • 3.2 const的使用
      • 4. 購物車案例
        • index.html
        • main.js
        • style.css
        • 效果圖
      • 5. JavaScript高階函數
        • filter()
        • map()
        • reduce()
        • 綜合
        • 簡化

  • mustache
    • {{}}
<div id="app">
  <h2>{{message}}</h2>
  <h2>{{message}},李銀河!</h2>
  <!-- mustache文法中,不僅僅可以直接寫變量,也可以寫簡單的表達式 -->
  <h2>{{firstName + lastName}}</h2>
  <h2>{{firstName + ' ' +lastName}}</h2>
  <h2>{{firstName}} {{lastName}}</h2>
  <h2>{{counter * 2}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!',
      firstName: 'kobe',
      lastName: 'bryant',
      counter:100,
    }
  })
</script>
           

  • v-once

    • 該指令後邊不需要跟任何表達式
    • 該指令表示元素群組件隻渲染一次,不會随着資料的改變而改變
<div id="app">
  <h2>{{message}}</h2>
  <h2 v-once>{{message}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!'
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)

  • v-html

    • 該指令後邊往往會跟上一個string類型
    • 會将string的html解析出來并且渲染
<div id="app">
  <h2>{{url}}</h2>
  <h2 v-html="url"></h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!',
      url: '<a href="https://www.baidu.com">百度一下<a/>'
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)

  • v-text

    • 該指令和Mustache比較相似:都是用于将資料顯示在界面中
    • 該指令通常情況下,接受一個string類型
  • 相對不靈活,不容易拼接内容,一般不用
<div id="app">
  <h2>{{message}},slience_me!</h2>
  <h2 v-text="message">,slience_me!</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!'
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)

  • v-pre

    :
    • 該指令用于跳過這個元素和它的子元素的編譯過程,用于顯示原本的

      Mustache

      文法
    • 原封不動的顯示出來
<div id="app">
  <h2>{{message}}</h2>
  <h2 v-pre>{{message}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!'
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)

cloak:鬥篷

  • v-cloak

    • 該指令防止不友好的{{message}}被看到
    • 不會看到{{}}内容
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    [v-cloak] {
      display: none;
    }
  </style>
</head>
<body>
<div id="app" v-cloak>
  <h2>{{message}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  //在vue解析之前,div有一個屬性v-cloak
  //在vue解析之後,div中沒有一個屬性v-cloak
  setTimeout(function () {
    const app = new Vue({
      el: '#app',
      data: {
        message: '你好啊!'
      }
    })
  }, 1000)

</script>
</body>
</html>
           
Vue基礎文法 ->(個人學習記錄筆記)
Vue基礎文法 ->(個人學習記錄筆記)

  • v-bind

    • 作用:動态綁定屬性
    • 縮寫:

      :

    • 預期:any(with argument) | Object (without argument)
    • 參數:attrOrProp(optional)
  • 例子:

    <img :src="imgURL" alt="">

<div id="app">
  <!--錯誤的文法:這裡不可以使用mustache文法-->
  <!--<img src="{{imgURL}}" alt="">-->
  <!--正确的做法:使用v-bind指令-->
  <img v-bind:src="imgURL" alt="">
  <a v-bind:href="aHref">百度一下</a>
  <!--  <h2>{{}}</h2>-->
  <br>
  <!--文法糖的寫法-->
  <img :src="imgURL" alt="">
  <a :href="aHref">百度一下</a>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!',
      imgURL:'https://cn.vuejs.org/images/logo.svg',
      aHref: 'https://www.baidu.com'
    }
  })
</script>
           

<div id="app">
<!--  <h2 class="active">{{message}}</h2>-->
<!--  <h2 :class="active">{{message}}</h2>-->
<!--  <h2 :class="{key1: value1,key2:value2}">{{message}}</h2>-->
<!--  <h2 :class="{類名1: boolean,類名2:boolean}">{{message}}</h2>-->
<!--  <h2 class="title" :class="{active: isActive,line:isLine}">{{message}}</h2>-->
  <h2 class="title" :class="getClasses()">{{message}}</h2>
  <button v-on:click="btnClick">按鈕</button>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!',
      isActive: true,
      isLine: true
    },
    methods:{
      btnClick:function (){
        this.isActive = !this.isActive
      },
      getClasses:function () {
        return {active: this.isActive,line: this.isLine}
      }
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)
Vue基礎文法 ->(個人學習記錄筆記)
<div id="app">
  <!-- 字元串 -->
  <h2 class="title" :class="['active', 'line']">{{message}}</h2>
  <!-- 變量 -->
  <h2 class="title" :class="[active, line]">{{message}}</h2>
  <h2 class="title" :class="getClasses()">{{message}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!',
      active: 'aaaa',
      line: 'bbbbbb'
    },
    methods: {
      getClasses: function () {
        return [this.active, this.line]
      }
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)
  • 點選哪個那個變紅
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .active{
        color: red;
    }
  </style>
</head>
<body>
<div id="app">
  <ul>
    <li v-for="(m, index) in movies" 
     	@click="liClick(index)" 
     	:class="{active:currentIndex===index}"> {{index}}-{{m}}</li>
  </ul>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      movies:['海王','海爾兄弟','火影忍者','進擊的巨人'],
      currentIndex: 0
    },
    methods:{
    	liClick(index){
			this.currentIndex = index;
		}
    }
  })
</script>
</body>
</html>
           
Vue基礎文法 ->(個人學習記錄筆記)
Vue基礎文法 ->(個人學習記錄筆記)

  • :style="{fontSize:finalSize + 'px',color:finalColor}"

  • style

    後邊跟的是一個對象類型
    • 對象的

      key

      CSS

      屬性名稱
    • value

      是具體賦的值,值可以來自于

      data

      中的屬性
<div id="app">
  <!--  <h2 :style="{key(屬性名): value(屬性值)}">{{message}}</h2>-->
  <!--  '50px'必須加上單引号,否則是當作一個變量去解析-->
  <!--<h2 :style="{fontSize: finalSize}">{{message}}</h2>-->
  <!-- finalSize當成一個變量使用 -->
  <h2 :style="{fontSize:finalSize}">{{message}}</h2>
  <h2 :style="{fontSize:finalSize + 'px',color:finalColor}">{{message}}</h2>
  <h2 :style="getStyles()">{{message}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!',
      // finalSize: '100px'
      finalSize: 100,
      finalColor: 'red'
    },
    methods:{
      getStyles:function () {
        return {fontSize:this.fontSize + 'px',backgroundColor: this.finalColor}
      }
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)
  • <div v-bind:style="[baseStyles, overridingStyles]"></div>

  • style

    後邊跟的是一個數組類型
    • 多個值以逗号

      ,

      分割即可
<div id="app">
  <h2 :style="[baseStyle,baseStyle1]">{{message}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!',
      baseStyle:{backgroundColor:'red'},
      baseStyle1:{fontSize:'100px'},
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)

  • 作用:綁定事件監聽器
  • @

  • 預期:Function|Inline Statement |Object
  • 參數: event

<div id="app">
  <h2>{{counter}}</h2>
  <!--  <button v-on:click="counter++">+</button>-->
  <!--  <button v-on:click="counter&#45;&#45;">-</button>-->
  <!--<button v-on:click="increment()">+</button>
  <button v-on:click="decrement()">-</button>-->
  <button @click="increment()">+</button>
  <button @click="decrement()">-</button>

</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      counter: 0
    },
    methods: {
      increment() {
        this.counter++;
      },
      decrement() {
        this.counter--;
      }
    }
  })
</script>
           

  • 情況一:如果該方法不需要額外參數,那麼方法後的()可以不添加
    • 但是注意:如果方法本身中有一個參數,那麼會預設将原生事件event參數傳遞進去
  • 情況二:如果需要同時傳入某個參數,同時需要event時,可以通過$event傳入事件
<div id="app">
  <!--事件調用的方法沒有參數-->
  <button @click="btn1Click()">按鈕1</button>
  <button @click="btn1Click">按鈕1</button>

  <!--在事件定義時,寫函數時省略了小括号,但是方法本身是需要參數的,這個時候,
  Vue會預設将浏覽器生産的event事件參數傳入到方法中-->
  <!--<button @click="btn2Click(123)">按鈕2</button>-->
  <!--<button @click="btn2Click()">按鈕2</button>-->
  <button @click="btn2Click">按鈕2</button>

  <!--方法定義時,我們需要event對象,同時又需要其他參數-->
  <!--在調用方法時,如何手動的擷取到浏覽器參數的event對象:-->
  <button @click="btn3Click(abc,$event)">按鈕3</button>
  <button>按鈕4</button>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!',
      abc: 123
    },
    methods:{
      btn1Click(){
        console.log('btn1Click');
      },
      btn2Click(event){
        console.log('btn2Click',event);
      },
      btn3Click(abc,event){
        console.log('btn3Click',abc,event);
      },
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)

  • Vue提供了修飾符來幫助我們友善的處理一些事件:
    • .stop

      調用

      event.stopPropagation()

      避免事件冒泡
    • .prevent

      event.preventDefault()

      阻止預設事件
    • .{keyCode|keyAlias}

      隻是事件從特定鍵觸發時才觸發回調 監聽鍵盤的某個鍵帽的點選
    • .native

      監聽元件根元素的原生事件
    • .once

      隻觸發一次回調
Vue基礎文法 ->(個人學習記錄筆記)

<div id="app">
  <h2 v-if="score>=90">優秀</h2>
  <h2 v-else-if="score>=80">良好</h2>
  <h2 v-else-if="score>=60">及格</h2>
  <h2 v-else>不及格</h2>
  ------------------------------------
  <h2>{{result}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      score: 88
    },
    computed:{
      result(){
        let showMessage = ''
        if (this.score>=90){
          showMessage = '優秀';
        }else if(this.score>=80){
          showMessage = '良好';
        }else if(this.score>=60){
          showMessage='及格';
        }else{
          showMessage='不及格';
        }
        return showMessage;
      }
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)
<div id="app">
  <span v-if="isUser">
    <label for="username">使用者賬号</label>
    <input type="text" id="username" placeholder="使用者賬号" key="username">
  </span>

  <span v-else>
    <label for="email">使用者郵箱</label>
    <input type="text" id="email" placeholder="使用者郵箱" key="email">
  </span>
  <button @click="isUser = !isUser">切換類型</button>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      isUser: true
    }
  })
</script>
           

  • v-if

    v-show

    都可以決定一個元素是否渲染,差別是:
    • v-if

      當條件為false時,壓根不會有對應的元素在DOM中
    • v-show

      當條件為false時,僅僅是将元素的

      display

      屬性設定為

      none

      而已
  • 開發中需要在顯示與隐藏之間切片很頻繁時建議選擇

    v-show

  • 隻有一次切換時,建議使用

    v-if

<div id="app">
  <!--v-if:當條件為false時,包含v-if指令的元素,根本就不會存在dom中-->
  <h2 v-if="isShow" id="aaa">{{message}}</h2>
  <!--v-show:當條件為false時,v-show隻是給我們的元素添加一個行内樣式:display:none-->
  <h2 v-show="isShow" id="bbb">{{message}}</h2>

</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!',
      isShow:true
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)

  • v-for

    的文法類似于

    javaScript

    中的

    for

    循環
  • 格式如下:

    item in items

    的形式
  • 如果便利的過程不需要索引值
    • v-for="movie in movies"

    • 依次從

      movies

      中取出

      movie

      ,并且在元素中,我們可以使用

      Mustache

      文法,來使用

      movie

  • 如果在周遊的過程中,我們需要拿到元素在數組中的索引值
    • 文法格式:

      v-for=(item, index) in items

    • 其中的

      index

      就代表了去除的

      item

      在原數組的索引值
  • 官方推薦我們在使用v-for時,給對應的元素或元件添加上一個

    :key

    屬性
  • key的主要作用是為了高效的更新虛拟DOM
  • 響應式的相關方法
    • push()

      在數組最後面添加元素
    • pop()

      删除數組最後面的元素
    • shift()

      删除數組的第一個元素
    • unshift()

      在數組最前面添加元素
    • splice()

      删除元素/插入元素/替換元素(start,num,value)
    • set()

      (要修改的對象,索引值,修改後内容)
    • sort()

      數組排序
    • reverse()

      數組反轉
      Vue基礎文法 ->(個人學習記錄筆記)
<div id="app">
  <!--1. 在周遊的過程中,沒有使用索引值(下标值)-->
  <ul>
    <li v-for="item in names">{{item}}</li>
  </ul>
  <!--2. 在周遊的過程中,擷取索引值(下标值)-->
  <ul>
    <li v-for="(item,index) in names">{{index+1}}. {{item}}</li>
  </ul>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      names:['why','kobe','james','curry']
    }
  })
</script>
           
<div id="app">
  <!--1. 在周遊對象的過程中,如果隻是擷取一個值,那麼擷取到的是value-->
  <ul>
    <li v-for="item in info">{{item}}</li>
  </ul>

  <!--2. 擷取key和value 格式:(value,key)-->
  <ul>
    <li v-for="(value,key,index) in info">{{value}}-{{key}}-{{index}}</li>
  </ul>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      info:{
        name:'why',
        age:18,
        height:1.88
      }
    }
  })
</script>
           
  • 綁定唯一key
<div id="app">
  <ul>
    <li v-for="item in letters" :key="item">{{item}}</li>
  </ul>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
     letters:['A','B','C','D','E']
    }
  })
</script>
           

<div id="app">
<!--  <input type="text" v-model="message">-->
<!--  <input type="text" :value="message" @input="valueChange">-->
  <input type="text" :value="message" @input="message = $event.target.value">
  {{message}}
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!'
    },
    methods:{
      valueChange(event){
        console.log('-----');
        console.log(event);
        this.message = event.target.value;
      }
    }
  })
</script>
           
<div id="app">
  <input type="text" v-model="message">
  {{message}}
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!'
    }
  })
</script>
           
<div id="app">
  <label for="male">
    <input type="radio" id="male" value="男" v-model="sex">男
  </label>
  <label for="female">
    <input type="radio" id="female" value="女" v-model="sex">女
  </label>
  <h2>您選擇的性别是: {{sex}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!',
      sex:'男',
    }
  })
</script>
           
<div id="app">
  <!--1. 單選框-->
  <label for="agreement">
    <input type="checkbox" id="agreement" v-model="isAgree">同意協定
  </label>
  <h2>您選擇的是:{{isAgree}}</h2>
  <button :disabled="!isAgree">下一步</button>

  <br>
  <!--2.多選框-->
  <label>
    <input type="checkbox" v-model="hobbies" value="籃球">籃球
    <input type="checkbox" v-model="hobbies" value="足球">足球
    <input type="checkbox" v-model="hobbies" value="乒乓球">乒乓球
    <input type="checkbox" v-model="hobbies" value="羽毛球">羽毛球
  </label>
  <h2>您的愛好是:{{hobbies}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!',
      isAgree:false,
      hobbies:[]
    },
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)
<div id="app">
  <!--1. 選擇一個-->
  <select name="abc" v-model="fruit">
    <option value="蘋果">蘋果</option>
    <option value="香蕉">香蕉</option>
    <option value="西瓜">西瓜</option>
    <option value="鳳梨">鳳梨</option>
  </select>
  <h2>您選擇是:{{fruit}}</h2>

  <br>
  <!--2. 選擇多個-->
  <select name="abc" v-model="fruits" multiple>
    <option value="蘋果">蘋果</option>
    <option value="香蕉">香蕉</option>
    <option value="西瓜">西瓜</option>
    <option value="鳳梨">鳳梨</option>
  </select>
  <h2>您選擇是:{{fruits}}</h2>

  <label v-for="item in originFruits" :for="item">
    <input type="checkbox" :value="item" :id="item" v-model="balls">{{item}}
  </label>
  <h2>您選擇是:{{balls}}</h2>

</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!',
      fruit: '香蕉', //單選框
      fruits:[], //多選框
      originFruits:['籃球','足球','乒乓球','羽毛球','撞球','高爾夫球'],
      balls:[],
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)
  • lazy

    修飾符:
    • 預設情況下,v-model預設是在input事件中同步輸入框的資料的
    • 一旦有資料發生改變對應的data中的資料就會自動發生改變
    • lazy修飾符可以讓資料失去焦點或者回車時才更新
<div id="app">
  <!--修飾符:lazy-->
  <input type="text" v-model.lazy="message">
  <h2>{{message}}</h2>

  <!--修飾符:number-->
  <input type="number" v-model.number="age">
  <h2>{{typeof age}}</h2>

  <!--修飾符:trim-->
  <input type="text" v-model.trim="name">
  <h2>{{name}}</h2>

</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊!'
    }
  })
</script>
           
  • number

    • 預設情況下,在輸入框中無論輸入字母還是數字,都被認為字元串處理
    • 如果希望是數字類型,最好直接将内容數字處理
    • number修飾符可以讓輸入框中的内容轉成數字類型
  • trim

    • trim修飾符可以去除兩側空格

<div id="app">
  <h2>{{firstName + ' ' + lastName}}</h2>
  <h2>{{firstName}} {{lastName}}</h2>
  <h2>{{getFullName()}}</h2>
  <h2 >{{fullName}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      firstName: 'Lebron',
      lastName: 'James'
    },
    computed:{
      fullName: function () {
        return this.firstName + ' ' + this.lastName;
      }
    },
    methods: {
      getFullName() {
        return this.firstName + ' ' + this.lastName;
      }
    }
  })
</script>
           

<div id="app">
  <h2>總價格:{{totalPrice}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      books: [
        {id: 110, name: 'Unix程式設計藝術', price: 119},
        {id: 111, name: '代碼大全', price: 105},
        {id: 112, name: '深入了解計算機原理', price: 98},
        {id: 113, name: '現代作業系統', price: 87},
      ]
    },
    computed: {
      totalPrice: function () {
        let result = 0
        for (let i=0; i<this.books.length;i++){
          result += this.books[i].price
        }
        return result

        // for (let i in this.books) {
        //   result += this.books[i].price
        // }
        //
        // for (let book of this.books) {
        //
        // }


      }
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)

  • 很好了解的

    setter

    getter

  • 一般隻是用

    getter

    來讀取,而

    setter

    不常用
<div id="app">
  <h2>{{fullName}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      firstName: 'kobe',
      lastName: 'Bryant'
    },
    computed:{
      // fullName:function (){
      //   return this.firstName + ' ' + this.lastName;
      // },
      // name: 'coderwhy',
      //計算屬性一般是沒有set方法,隻讀屬性
      fullName:{
        set:function (newValue) {
          console.log("---------"+ newValue);
          const names = newValue.split(' ');
          this.firstName = names[0];
          this.lastName = names[1];
        },
        get:function () {
          return this.firstName + ' ' + this.lastName;
        }
      },
      // fullName:function () {
      //     return this.firstName + ' '  + this.lastName;
      //   }
    }
  })
</script>
           

  • methods

    computed

    都可以實作功能
  • 計算屬性會進行緩存,如果多次使用時,計算屬性隻調用一次
  • computed

    效率高
<div id="app">
  <!-- 1. 直接拼接 : 文法過于繁瑣3-->
  <h2>{{firstName}} {{lastName}}</h2>

  <!-- 2. 通過定義methods -->
  <h2>{{getFullName()}}</h2>
  <h2>{{getFullName()}}</h2>
  <h2>{{getFullName()}}</h2>
  <h2>{{getFullName()}}</h2>
  <h2>{{getFullName()}}</h2>

  <!-- 3. 通過computed -->
  <h2>{{fullName}}</h2>
  <h2>{{fullName}}</h2>
  <h2>{{fullName}}</h2>
  <h2>{{fullName}}</h2>
  <h2>{{fullName}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      firstName: 'kobe',
      lastName: 'Bryant'
    },
    methods: {
      getFullName() {
        console.log('getFullName');
        return this.firstName + ' ' + this.lastName;
      }
    },
    computed: {
      fullName: function () {
        console.log('fullName');
        return this.firstName + ' ' + this.lastName;
      }
    }
  })
</script>
           
Vue基礎文法 ->(個人學習記錄筆記)

  • 事實上var的設計可以看成JavaScript語言設計上的錯誤,但是這種錯誤多半不能修複和移除,以為需要向後相容
    • 大概十年前,Brendan Eich 就決定修複這個問題,于是他添加了一個新的關鍵詞:

      let

  • 塊級作用域
    • JS中使用var來聲明一個變量時,變量的作用域主要是和函數的定義有關
    • 針對于其他塊定義來說是沒有作用域的,比如if/for等,這在我們開發中往往會引起一些問題
  • ES5之前因為if和for都沒有塊級作用域的概念,是以在很多時候,我們都必須借助于function的作用域來解決應用外面變量的問題
<script>
  // 1.變量作用域:變量在什麼範圍内是可用的
  // {
  //   var name = 'why'
  //   console.log(name);
  // }
  // console.log(name);

  //2.沒有塊級作用域引起的問題 if 的塊級
  // var func;
  // if (true){
  //   var name = 'why';
  //   func = function () {
  //     console.log(name);
  //   }
  //   func()
  // }
  // console.log(name);

  //2.沒有塊級作用域引起的問題 for 的塊級
  var btns = document.getElementsByTagName('button');
  for (var i = 0; i < btns.length; i++) {
    (function (i) {
      btns[i].addEventListener('click', function () {
        console.log('第' + (i + 1) + '個按鈕被點選');
      })
    })(i)
  }
  const btns = document.getElementsByTagName('button');
  for (let i = 0; i < btns.length; i++) {
      btns[i].addEventListener('click', function () {
        console.log('第' + (i + 1) + '個按鈕被點選');
      })
  }
</script>
           

  • const關鍵字
    • 将某個變量變為常量
    • 在js中,使用其辨別後,不可再次指派
  • 不可修改
  • 定義必須指派

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
  <div v-if="books.length">
    <table>
      <thead>
      <tr>
        <th></th>
        <th>書籍名稱</th>
        <th>出版日期</th>
        <th>價格</th>
        <th>購買數量</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(item,index) in books">
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.date}}</td>
        <td>{{item.price | showPrice}}</td>
        <td>
          <button @click="decrement(index)" :disabled="item.count <= 1">-</button>
          {{item.count}}
          <button @click="increment(index)">+</button>
        </td>
        <td>
          <button @click="removeHandle(index)">移除</button>
        </td>
      </tr>
      </tbody>
    </table>
    <h2>總價格:{{totalPrice}}</h2>
  </div>
  <h2 v-else>購物車為空</h2>
</div>
<script src="../js/vue.js"></script>
<script src="main.js"></script>
</body>
</html>
           

const app = new Vue({
  el: '#app',
  data: {
    books: [
      {
        id: 1,
        name: '《算法導論》',
        date: '2006-9',
        price: 85.00,
        count: 1
      },
      {
        id: 2,
        name: '《UNIX程式設計藝術》',
        date: '2006-2',
        price: 59.00,
        count: 1
      },
      {
        id: 3,
        name: '《程式設計珠玑》',
        date: '2006-10',
        price: 39.00,
        count: 1
      },
      {
        id: 4,
        name: '《代碼大全》',
        date: '2006-3',
        price: 128.00,
        count: 1
      }
    ]
  },
  computed: {
    totalPrice() {
      // 1.普通for循環
      let totalPrice = 0;
      // for (let i = 0; i < this.books.length; i++) {
      //   totalPrice += this.books[i].count * this.books[i].price;
      // }
      // return totalPrice;

      //2. for(let i in this.books)
      // for (let i in this.books) {
      //   totalPrice += this.books[i].count * this.books[i].price;
      // }
      // return totalPrice;

      // for(let i in/of this.books)
      for(let item of this.books){
        console.log(i);
        totalPrice += item.count * item.price;
      }
      return totalPrice;
    },
  },
  methods: {
    // getFinalPrice(price){
    //   return '¥'+ price.toFixed(2);
    // }
    increment(index) {
      this.books[index].count++;
    },
    decrement(index) {
      this.books[index].count--;
    },
    removeHandle(index) {
      this.books.splice(index, 1)
    }
  },
  filters: {
    showPrice(price) {
      return '¥' + price.toFixed(2);
    }
  }
})
           

table{
    border: 1px solid #e9e9e9;
    border-collapse: collapse;
    border-spacing: 0;
}

th,td{
    padding: 8px 16px;
    border: 1px solid #e9e9e9;
    text-align: left;
}

th{
    background-color: #f7f7f7;
    color: #5c6b77;
    font-weight: 600;
}
           

Vue基礎文法 ->(個人學習記錄筆記)
Vue基礎文法 ->(個人學習記錄筆記)

如果為空

Vue基礎文法 ->(個人學習記錄筆記)

const nums=[10,20,30,40,50,222,50,15]
let newNums = nums.filter(function (n) {
  return n>=100;
})
//newNums = [10, 20, 40, 50]
           

const newNums = [10, 20, 40, 50]
let new2Nums = newNums.map(function (n) {
  return n*2;
})
//new2Nums= [20, 40, 80, 100]
           

new2Nums= [20, 40, 80, 100]
let total = new2Nums.reduce(function (preValue,n) {
  return preValue + n;
}, 0)
//240
           

const nums=[10,20,111,222,444,40,50]

let total = nums.filter(function (n) {
  return n < 100;
}).map(function (n) {
  return n*2;
}).reduce(function (preValue,n) {
  return preValue + n;
}, 0)

console.log(total);
           

const nums=[10,20,111,222,444,40,50]
let total = nums.filter(n => n<100).map(n => n * 2).reduce((pre, n) => pre + n);
console.log(total);