vue的常用组件方法应用

项目技术:

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

 

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:

  相当于jq 中的 dom 字符串

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

  原生的js 往数组里压入和弹出 数据(抓数组的长度),因为vue的是以数据驱动,以数据判断,该不该渲染dom

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

 

4. 追加class , 场景 在循环某个列表时候,某个列表有class,绑定一个方法,可以支持穿参数

dom

 

<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>

js

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

5.子->父组件的通信,vue.$emit vue.on 

把子组件的 '**@课程‘ 传递给父组件

子组件:

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 的挂载

 

12、给当前点击的元素添加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>

 

posted @ 2017-11-28 19:13  adouwt  阅读(2585)  评论(0编辑  收藏  举报