vue的經常使用組件方法應用

項目技術:javascript

webpack + vue + element(mint-ui, etc...) + axois (vue-resource) + less-loader+ ...css

 

vue的操做的方法案例:前端

1.數組數據還未獲取到,作出預加載的動畫

<el-carousel :interval="3000" type="card" height="200px" class="common-mt-md">
      <el-carousel-item v-for="item in movieArr" :key="item.id" class="text-center">
        <img v-bind:src="item.images.small" alt="電影封面" class="ticket-index-movie-img">
      </el-carousel-item>// 實際顯示的內容-跑馬燈
      <div v-if="!movieArr.length" class="ticket-index-movie-loading">
        <span class="el-icon-loading "></span>
      </div>// 當 movirArr的數組爲空的時候,作出的預加載 loading 
</el-carousel>

2. 按鈕狀態的判斷,按鈕能不能點的問題

<p v-if="!multipleSelection.length">
    <el-button type="success" round disabled>導出</el-button>
</p><!-- 不能點, 判斷數組爲空 -->
<p v-else>
    <el-button type="success" round >導出</el-button>
</p><!-- 能夠點, 判斷數組爲不爲空 -->
 

3.像jquery 同樣,追加dom (vue 是以數據爲導向的,應該擺脫jquery的 dom的繁雜操做)

<el-form-item label="時間" prop="name">
    <el-input v-model="ruleForm.name"></el-input>//綁定模型,檢測輸入的格式
    <span class="el-icon-plus ticket-manage-timeinput" @click="addTime(this)"></span>//綁定方法,增長dom的操做
 </el-form-item> 
<el-form-item label="時間" prop="name" v-for="item in timeArr" :key='item.id'> //timeArr數組與數據就渲染下面的dom,沒有就不顯示
  <el-input v-model="ruleForm.name"></el-input>
  <span class="el-icon-minus ticket-manage-timeinput" @click="minusTime(this)"></span>
</el-form-item>

js:vue

  至關於jq 中的 dom 字符串java

 timeInputString: '<el-input v-model="ruleForm.name"></el-input><span class="el-icon-minus"></span>'

  原生的js 往數組裏壓入和彈出 數據(抓數組的長度),由於vue的是以數據驅動,以數據判斷,該不應渲染domjquery

 addTime () {
  this.timeArr.push('str')
 },
 minusTime () {
  this.timeArr.shift('str')
 }

 

4. 追加class , 場景 在循環某個列表時候,某個列表有class,綁定一個方法,能夠支持穿參數

domwebpack

 

<li v-for="section in item.sections" :key='section.id' @click="hideParMask" :class="getSectionId(section.id)">
 <router-link :to="{ name: 'learning', params: { sectionId: section.id}, query: { courseId: courseId}}" >
     <span>{{item.orderInCourse}}.{{section.sectionNumber}}</span>
     <span>{{section.name}}</span>
 </router-link>
</li>

jsweb

getSectionId (sectionId) {
 return {
   active: this.$route.params.sectionId === sectionId,
 }
}

5.子->父組件的通訊,vue.$emit vue.on 

把子組件的 '**@課程‘ 傳遞給父組件vue-router

子組件:vuex

created () {
 this.sendNameToparent();
},
   methods:{ 
  sendNameToparent () {
    this.$emit(' receiveTitle', '**@課程')
  }
 }

父組件:

dom

<v-child :courseId="courseId" v-on:receiveTitle="receiveTitle"></v-child>

js

methods: {
  receiveTitle (name) {
   this.titleName = name; // titleName 就是 **@課程   ,name參數 就是子組件傳遞過來的值
  } 
}

 總結套路: 子組件使用函數(事件)給父組件傳遞 receiveTitle 屬性,而後父組件監測這個屬性,給這個屬性綁定方法 receiveTitle,方法傳參數,這個參數就是 要傳遞的 值

6.父-> 子

父組件:

dom:

<course-tab :courseList = courseList ></course-tab>

js:

courseList().then(res => {
  this.courseList = res.data.courses;
 }).catch( err => {
  console.log(err)
});

子組件:

 props: {
    courseList: {
      type: Array
    }
  }

總結套路:父組件將變量傳到子組件,須要在子組件標籤上綁定這個變量,而後子組件就能夠在props 裏接受這個變量

 7.錯誤路由的處理,重定向, 在router裏添加一個路由信息

{
    path: '*',
    redirect: '/'
}

這裏是從新定向到首頁,也能夠單獨作一個 404頁面,重定向到這個頁面

編程式導航裏面,

router.push({ path: 'login-regist' })   //  若是這樣寫的話,會尋找路由最近的 / 而後在後面直接拼接login-regist;
爲了防止在多級嵌套路由裏面出現bug ,應該寫全路由的所有信息,包括  /
router.push({ path: '/login-regist' })  

 8. dom 裏拼接css 

<div class="img" :style="{background: 'url(' + item.logoFileURL + ')'}"></div>

 9. 監聽滾動事件

data () {
    return {
      scrolled: false,
    show: true
} },
methods: {
    handleScroll () {
      this.scrolled = window.scrollY > 0;
      if (this.scrolled) {
        this.show = false;
      }
    }
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll);
  }

10.監聽輸入框輸入值的變化

@input="search",
監聽 element-UI 的<el-input  的方法,
<el-input v-model="input" @keyup.enter.native="add" placeholder="請輸入內容" ></el-input>

 

11.某種需求在某個組件裏給body追加樣式或者class,到其餘頁面這個樣式或者class 再去掉,由於是單頁面,js追加上樣式後在不刷新的基礎上,這些class或者樣式是不會消失的,因此須要依賴vue的聲明周期函數將其組件銷燬,以避免污染整個應用

mounted () {
    document.body.style.backgroundColor = '#332f86'
 },

destroyed () {
    document.body.style.backgroundColor = 'transparent'
},

注意: 給body 追加背景顏色必須是在mounted 這個周期函數鉤子裏,放在created 這個方法不行,由於created 時候,el(理解爲dom)尚未造成,mounted 時候完成的dom 的掛載

 

十二、給當前點擊的元素添加class

dom:

<p v-for="(val, index) in currentQueation.answers" :key='val.id'>
     <span class="answer-item-wrapper" :class="{ active: chooseNum === index }" @click="selectItem(index, currentQueation.rightAnswer)">
       <span class="select-wrapper">
       </span>
       <span class="select-content">
              {{val}}
      </span>
    </span>
</p>

js:

data () {
  return {
     // ...
    chooseNum : ''
  }
}
methods: {
      // ....
    selectItem (type, rightVal) {
      this.chooseNum = type
    // ...         
}

// 理解: 
 由於列表是循環渲染出來的,這樣每一個 item 就有對應的 index, 而後咱們點擊某個對應的 index選項的時候,就會獲取到他的type (就是index,咱們在方法中傳值過去), 
index獲取到了,咱們就能夠拿這個點擊的index 和他循環的index進行比較,若是相等,則表示我當前點擊的對象   能夠追加 active, :
class="{ active: chooseNum === index }"

 

13. 給標籤上拼 字符串 +變量

<van-cell v-for= '(item, i) in arguementListData' :key="i" :title="'《' + item.name + '》'" is-link to="item.url"/>

 14.點擊收起和隱藏方法

  說到底仍是控制dom 顯示和隱藏的方法。顯示不一樣的數組,也能夠直接在頁面顯示dom,經過v-show 顯示或者隱藏,若是經過數組方式,也能夠再點擊的時候,向數組裏面push 和pop 數組內容,數據是雙向綁定的,數組中的數據有變化,dom也會及時顯示出來

  點擊收起按鈕時候 ,更改 toggle 布爾值 

<ol v-show="toggle">
    <li v-for = "item in ruleData" :key="item"> {{item}}</li>
</ol>
<ol v-show="!toggle">
    <li v-for = "item2 in allRuleData" :key="item2">{{item}}</li> 
</ol>

15.阻止彈框滾動

 <div class="wx-model" v-show="wxShow" @touchmove.prevent>
 </div>

16. 格式化電話號碼,格式爲 188 8888 8888

dom:

<input type="tel" v-model="tel"  maxlength="13" minlength="13" ref="input"  required>

js:

watch: {
  tel (newValue, oldValue) {
    if (newValue > oldValue) {
    if (newValue.length === 4 || newValue.length === 9) {
      var pre = newValue.substring(0, newValue.length - 1)
      var last = newValue.substr(newValue.length - 1)
       this.tel = pre + ' ' + last
    } else {
       this.tel = newValue
    }
   } else {
    if (newValue.length === 9 || newValue.length === 4) {
        this.tel = this.tel.trim()
    } else {
        this.tel = newValue
    }
      }
  }
},
 
 
watch: {
  if (newValue.length > oldValue.length) {
     this.tel = newValue.replace(/\s/g, '').replace(/(\d{3})(\d{0,4})(\d{0,4})/, '$1 $2 $3')
  } else {
     this.tel = this.tel.trim()
  }
}

 

 

17.銀行卡號 四位一空格

card (newValue, oldValue) {
 if (newValue > oldValue) {
 // 8888 8888 8888 8888 8888
  if (newValue.length === 5 || newValue.length === 10 || newValue.length === 15 || newValue.length === 20) { // 根據卡的位數繼續寫這樣的判斷
    newValue = newValue.replace(/\s/g, '').replace(/[^\d]/g, '').replace(/(\d{4})(?=\d)/g, '$1 ')
     // newValue = newValue.replace(/\s/g, '').replace(/[^\d]/g, '').replace(/(\d{4})(?=\d)/g, '$1-') 8888-8889-5555
 this.card = newValue } else { this.card = newValue } } else { if (newValue.length === 5 || newValue.length === 10 || newValue.length === 15 || newValue.length === 20) { this.card = this.card.trim() } else { this.card = newValue } }
}

 正則匹配

watch: {
  if (newValue.length > oldValue.length) {
     this.tel = newValue.replace(/\s/g, '').replace(/(\d{4})/g, '$1 ')
  } else {
     this.tel = this.tel.trim()
  }
}

 

18. vue 路由切換,頁面沒有滾動到頂部

  vue-router的模式是 hash ,(另外一種是history)

mounted () {
        document.querySelector('#app').scrollIntoView()
}

scrollIntoView 的介紹: https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView
 

19.前端幾個頁面存儲值到vuex 上的時候,要考慮頁面是否刷新,從vuex上狀態樹 state上取值有影響,存在刷新而且沒有數據庫的狀況下,考慮使用h5的 store

20. 父組件調用子組件的方法

子組件:

<template>
    <div>
        child1
    </div>
</template>

<script>
    export default {
        name: "child1",
        props: "msg",
        methods: {
            handleParentClick(e) {
                console.info(e)
            }
        }
    }
</script>

父組件:

<template>
    <div>
        <button v-on:click="clickParent">點擊</button>
        <child1 ref="child1"></child1>
    </div>
</template>

<script>
    import Child1 from './child1';
    export default {
        name: "parent",
        components: {
            child1: Child1
        },
        methods: {
            clickParent() {
                // this.$refs.child1.$emit('click-child', "high");
                this.$refs.child1.handleParentClick("ssss");
            }
        }
    }
</script>
相關文章
相關標籤/搜索