顯示具有 [前端工程]Vue框架 標籤的文章。 顯示所有文章
顯示具有 [前端工程]Vue框架 標籤的文章。 顯示所有文章

2019年3月6日 星期三

【Vuex】Store的寫法:mutation、action、payload


▌Store寫法

  • state:資料的狀態
  • mutations:改變state的值,
    increment(state){
    this.state.count++ 
    }
    
  • actions:去commit mutation
    increment:({commit})=>commit("increment")
    

▌vue寫法

  • this.$store.dispatch(“action的名稱”)
    increment(){
    this.$store.dispatch("increment")
    }
    
  • this.$store.commit(“mutation的名稱”)
    increment(){
    this.$store.commit("increment")
    }
    

▌範例

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state={
  num:0
}

const mutations={
  increment(state){
    state.num ++
  },
  descrement(state){
    state.num --
  }
}

const actions ={
  increment:({commit})=> commit("increment"),
  descrement:({commit})=> commit("descrement")
}

export default new Vuex.Store({
  state,
  mutations,
  actions
})

載荷寫法 Payload

▌vue

-vue:descrement ( ){ this.$store.dispatch(“descrement”,this.pay) }
  descrement(){
    this.$store.dispatch("descrement",this.pay)
  }
  increment(){
    this.$store.dispatch("increment",this.pay)
  }

▌store

  • action: increment:({commit},payload)=> commit(“increment”,payload),
  • mutation:increment(state,payload){ state.num +=payload}
const state={
  num:0
}

const mutations={
  increment(state,payload){
    state.num +=payload
  },
  descrement(state,payload){
    state.num -=payload
  }
}

const actions ={
  increment:({commit},payload)=> commit("increment",payload),
  descrement:({commit},payload)=> commit("descrement",payload)
}

2019年3月3日 星期日

【專案建構】用Vue Cli快速建立專案:包括Typescript、SCSS、Router....



最近一直在研究如何在vue專案中使用Typescript,結果設定的好累,都不知道自己在幹嘛。後來發現其實只要用最新版本的@vue/cli 3.x ,一下就可以解決了…..
https://cli.vuejs.org/zh/guide/

▌@vue/cli 是什麼

跟2.0不一樣,它可以事前就選擇套件Typescript、SCSS、Router,可以不用在事後安裝

▌安裝

啟用

yarn global add vue-cli //先安裝vue cli
vue create 專案名稱
vue ui //可以用ui 選擇各種要用的內容

常見套件

axios
bootstrap
jquery
vue-loading-overlay



2018年7月21日 星期六

【Vue】Component區域註冊、全域註冊、x-template


1.區域註冊 (寫在new Vue裡面)

    <div id="app">
        <people v-for="item in data" :people="item"> </people>
    </div>

    var app = new Vue({
        el: '#app',
        data: {
            data: [{
                name: "jack",
                age: 20
            }, {
                name: "neo",
                age: 23
            }, {
                name: "hao",
                age: 25
            }]
        },
        components: {
            'people': {
                template: '<ul><li>{{people.name}}</li><li>{{people.age}}</li></ul>',
                props: ["people"]
            }
        } 寫在這裡,如果有一個新的vue,或是領域之外的東西就無法用
    })

2.全域註冊 Vue.components

    <div id="app">
        <people v-for="item in data" :people="item"> ->接收item的資料傳到[people] </people> 
    </div>

    Vue.component(
         'people': {
                template: '<ul><li>{{people.name}}</li><li>{{people.age}}</li></ul>',
                props: ["people"] 陣列接收資料
            }
        } 全域註冊,就可以隨便用。
    )

   var app = new Vue({
        el: '#app',
        data: {
            data: [{
                name: "jack",
                age: 20
            }, {
                name: "neo",
                age: 23
            }, {
                name: "hao",
                age: 25
            }]
        })

3.使用x-template

把模板放在template太難維護了,放在script好了
    <div id="app">
        <people v-for="item in data" :people="item"> </people>
    </div>

<script type="text/x-template" id="people">
    <ul>
        <li>{{people.name}}</li>
        <li>{{people.age}}</li>
    </ul>
</script>
    Vue.component(
        'people', {
            template: "#people",
            props: ["people"]
        }
    )

   var app = new Vue({
        el: '#app',
        data: {
            data: [{
                name: "jack",
                age: 20
            }, {
                name: "neo",
                age: 23
            }, {
                name: "hao",
                age: 25
            }]
        })

2018年7月20日 星期五

【Vue】生命週期created、mounted、updated、activated


生命週期

beforeCreate
created:建構資料
beforeMount
mounted:掛載元件,然後開始渲染
updated
activated
deactivated:元件消失,但資料不會消失
beforeDestroy
destroyed
html加上 就不會destroyed,而是變成deactivated
要用AJAX至少要等到created階段或是mounted階段

【vue】表格排序的寫法:icon的運用+sort()排序

表格排序




範例:https://codepen.io/NishanYeah/pen/YjNPgx

箭頭的的icon

  • 貼入fontawesome css
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.1/css/all.css" crossorigin="anonymous">
  • 複製箭頭icon的標籤放到span當中

<span >
              <i class="fas fa-angle-up"></i>
</span>

  • 製作reverse的class,讓icon可以倒轉180deg

.reverse {
            transform: rotate(180deg)
        }
用:class切換reverse的數值
 <span class="icon" :class="{'reverse':iconreverse_left}">
                            <i class="fas fa-angle-up"></i>
 </span>

sort排序的原理

  • 預設是根據ASCII編碼排序A->Z or 1->9

data.sort(sortgogo)  //如果得到正值就從小排到大,負值就大牌到小
sortgogo = function(a,b){
  return a-b
}

數據排序

 var app = new Vue({
            el: "#app ",
            data: {
                menu: [{
                        name: "川菜",
                        price: 200,
                        discount: 3
                    },
                    {
                        name: "漢堡",
                        price: 70,
                        discount: 5
                    },
                    {
                        name: "冰咖啡",
                        price: 40,
                        discount: 10
                    }, {
                        name: "奶茶",
                        price: 100,
                        discount: 10
                    }, {
                        name: "稀飯",
                        price: 900,
                        discount: 100
                    }, {
                        name: "大奶包",
                        price: 20,
                        discount: 10
                    },
                ],
                iconreverse_right: false,
                iconreverse_left: false,
                pricepriorty: true,
                priceup: true,
                discountup: true

            },
            computed: {
                newarray: function () {
                    var vm = this;
                    pricesort = function (a, b) {
                        if (vm.priceup) {
                            return a.price - b.price
                        } else return b.price - a.price
                    }
                    discountsort = function (a, b) {
                        if (vm.discountup) {
                            return a.discount - b.discount
                        } else return b.discount - a.discount
                    }
                    if (vm.pricepriorty) {
                        return vm.menu.sort(pricesort)
                    } else return vm.menu.sort(discountsort)
                }
            }

        })

三元運算符和[]寫法


<body>
    <div id="app">

        <div class="container mt-5">
            <table class="table table-striped">
                <thead class="thead-dark">
                    <th>商品
                    </th>

                    <th class="click" @click="iconreverse_left=!iconreverse_left,priority='price',ASC=-1*ASC">價格
                        <span class="icon" :class="{'reverse':iconreverse_left}">
                            <i class="fas fa-angle-up"></i>
                        </span>
                    </th>
                    <th class="click" @click="iconreverse_right=!iconreverse_right,priority='discount',ASC=-1*ASC"> 折扣
                        <span class="icon" :class="{'reverse':iconreverse_right}">
                            <i class="fas fa-angle-up"></i>
                        </span>
                    </th>
                </thead>
                <tbody>
                    <tr v-for="item in newarray">
                        <td>{{item.name}}</td>
                        <td>{{item.price}}</td>
                        <td>{{item.discount}}</td>
                    </tr>
                </tbody>
            </table>
        </div>

    </div>
</body>

<script>
    var app = new Vue({
        el: "#app ",
        data: {
            menu: [{
                name: "川菜",
                price: 200,
                discount: 3
            }, {
                name: "漢堡",
                price: 70,
                discount: 5
            }, {
                name: "冰咖啡",
                price: 40,
                discount: 10
            }, {
                name: "奶茶",
                price: 100,
                discount: 10
            }, {
                name: "稀飯",
                price: 900,
                discount: 100
            }, {
                name: "大西瓜",
                price: 20,
                discount: 10
            }, ],
            iconreverse_right: false,
            iconreverse_left: false,
            priority: 'price',
            ASC: 1,

        },
        computed: {
            newarray: function () {
                var vm = this;
                return vm.menu.sort(function (a, b) {
                    var a = a.[vm.priority]
                    var b = b.[vm.priority]
                    return (a === b ? 0 : a > b ? vm.ASC * 1 : vm.ASC * -1)
                });
            }

        }
    })

【Vue】keyup+編碼或是別名修飾/@click+左右鍵/一些修飾符


keyup+編碼或是別名修飾

  • keyup+鍵盤編碼(比如說13代表enter)
  • keyup+別名修飾 (enter, .tab, .delete, .esc, .space, .up, .down, .left, .right .ctrl, .alt, .shift, .meta)
<input type="text" v-model="text" @keyup.13="trigger(13)"> //13代表enter
<input type="text" v-model="text" @keyup.space="trigger('space')">

@click+左右鍵

  • @click+medium/right/left
  <span class="box" @click.right="trigger('Right button')">

@click=”storeMoney(item)”

<li v-for="item in arrayData" class="my-2">
              {{ item.name }} 有 {{ item.cash }} 元
              <button class="btn btn-sm btn-outline-primary" @click="storeMoney(item)">儲值</button>
            </li>
storeMoney: function (item) {
                item.cash = item.cash + 500;
              },

一些可能會用到的修飾符

.stop - 調用 event.stopPropagation()。
.prevent - 調用 event.preventDefault()。
.capture - 添加事件偵聽器時使用 capture 模式。
.self - 只當事件是從偵聽器綁定的元素本身觸發時才觸發回調。
.once - 只觸發一次回調。

【Vue】Select>option選擇題結構 / true(false)-value真假傳值 / v-model.lazy懶惰 / v-model.trim去除空白




選擇題

  • select>option
  • select和資料串接,然後option的value會傳到select的資料裡
 <h1>請選擇</h1>
        <select name="" id="" v-model="likeperson">
            <option value="" disabled>請選擇</option>
            <option value="小明">小明</option>
            <option value="小黃">小黃</option>
            <option value="小紅">小紅</option>
        </select>
        <br>
  <span>喜歡的人是{{likeperson}}</span>

選擇題(選項放陣列中)

  • :value要記得加:
  • 把選項放到陣列中,然後渲染多個選項
        <h1>請選擇</h1>
        <select name="" id="" v-model="likeperson2">
            <option value="" disabled>請選擇</option>
            <option v-for="item in alotperson" :value="item">{{item}}</option>
        </select>
alotperson: ['小明', '小黃', '小紅'],



true-value / false-value

  • input>label結構
  • 當資料為true時,value傳男;當資料為false,value傳女
        <h1>性別</h1>
        <input type="checkbox" v-model="sex" true-value="男" false-value="女">
        <label for=" ">{{sex}}</label>

sex: '男'

v-model.lazy

  • v-model.lazy可以讓資料在輸入完畢後再顯示
<h4>懶惰</h4>
<h5> {{lazy}}</h5>
<input type="text" v-model.lazy="lazy">
lazy: ''

v-model.trim

  • v-model.trim可以ㄅㄚ
        <h4>緊縮</h4>
        <h5> {{lazy}}</h5>
        <input type="text" v-model.trim="lazy">

【Vue】computed與methods的差別& watch(監視)


computed

  • methods的啟用需要仰賴「事件觸發」,但computed的則會直接return資料
  • 每個computed的function都要return一個資料
vue
filterarray: function () {
                    var vm = this
                    return vm.alldata.filter(function (item) {
                        return vm.alldata.match(vm.filtertext)
                    })
                }
html
<p>使用 Computed 來過濾資料。</p>
          <input type="text" class="form-control" v-model="filterText">
          <ul>
            <li v-for="(item, key) in filterArray" :key="item.age">
              {{ key }} - {{ item.name }} {{ item.age }} 歲
              <input type="text">
            </li>
</ul>

watch

  • watch一但發現某個資料發生變化,立即啟用function

watch: {
        trigger: function () {  //監測trigger資料是否變化,就執行function
                  var vm = this
                  setTimeout(() => {
                        vm.trigger = false
                    }, 3000);
                }
            }

2018年7月19日 星期四

【Vue】V-if 顯示/不顯示、頁籤的功能 /v-else-if是什麼?/ :key很重要/ v-show跟v-if的差別




v-if / v-else-if

  • v-if= true則顯示dom元素/false則移除dom元素
  • v-else-if 跟鄰近的v-if連動
          <div v-if="isSuccess">成功!</div>
          <div v-else-if="!isSuccess">失敗!</div>
           <input type="checkbox" id="isSuccess" v-model="isSuccess"> //連結v-model資料
            data: {
              isSuccess: true,
            }

v-else-if做籤頁

  • 記得用click.prevent阻止他往上跑
  • 籤頁u要用:class=”{‘active’:link == ‘a’} 轉換active
<ul class="nav nav-tabs">
            <li class="nav-item">
              <a class="nav-link" href="#" :class="{'active':link == 'a'}" @click.prevent="link = 'a'">標題一</a>    //點擊時就把link轉成a,還有套用active的class
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#" :class="{'active':link == 'b'}" @click.prevent="link = 'b'">標題二</a>  //點擊時就把link轉成b,還有套用active的class
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#" :class="{'active':link == 'c'}" @click.prevent="link = 'c'">標題三</a>   //點擊時就把link轉成c,還有套用active的class
            </li>
          </ul>

<div class="content">
            <div v-if="link == 'a'">A</div>   // v-if 的link如果是a 就顯示A
            <div v-if="link == 'b'">B</div>  // v-if 的link如果是b 就顯示B
            <div v-if="link == 'c'">C</div>  // v-if 的link是c 就顯示C
</div>





:key

  • 如果沒有加:key ,v-if不會把他置換
<template v-if="loginType === 'username'">
            <label>Username</label>
            <input class="form-control" placeholder="Enter your username" :key="1">
          </template>
          <template v-else>
            <label>Email</label>
            <input class="form-control" placeholder="Enter your email address" :key="2">
</template>

v-show和v-if的差別

  • v-show是用display:none切換的方式讓東西消失
  • v-if是直接把dom元素放置和移除

      <div class="alert alert-success" v-show="isSuccess">成功!</div>
      <div class="alert alert-danger" v-show="!isSuccess">失敗!</div>
      <div class="form-check">
        <input type="checkbox" class="form-check-input" id="isSuccess2" v-model="isSuccess">
        <label class="form-check-label" for="isSuccess2">啟用元素狀態</label>
      </div>
    </div>







template

  • template不會被渲染
           <template v-if="showTemplate">
              <tr>
                <td>1</td>
                <td>安妮</td>
              </tr>
              <tr>
                <td>2</td>
                <td>小明</td>
              </tr>
            </template>
            data: {
             showTemplate: true,
            }


【Vue】數字迴圈、template、V-if


數字迴圈

  • 可以輸出數字
<ul>
   <li v-for="item in 10">{{item}}</li>
</ul>
1
2
3
4
5
6
7
8
9
10

template

  • template不會被輸出
 <template v-for="(item, key) in member">
            <tr>
                <td>{{ item.name }}</td>
            </tr>
            <tr>
                <td>{{ item.age }}</td>
            </tr>
 </template>

v-if

  • 如果v-if等於,就輸出
 <div v-for="(item, key) in member" v-if="item.age==23">
            <li>{{item.name}}</li>
 </div>

【JavaScript】用物件Mapping的方法

If的寫法 我們希望當變數是a時就回傳1,變數是b就回傳2,變數是c就會回傳3,一般寫法就是用if,但是這樣會很冗 ​ // IF style var word if(word == 'a'){ word = 1 } else if...