vue常用方法以及面试问题

vue移动端ui库: http://mint-ui.github.io/#!/zh-cn  vant

vue做app开发使用: weex 官网地址:http://weex.apache.org/cn

一、Vue class 和 style

页面中动态控制样式

<div class="hello">
        class 和 style
        <p :class="{ black: isBlack, yellow: isYellow }">1、使用class</p>
        <p :class="[black, yellow]">2、数组</p>
        <p :class="styleData">3、引用方式</p>
    </div>
data() {
        return {
            isBlack: true,
            isYellow: true,
            black: 'black',         // 这里black yellow 是 class name
            yellow: 'yellow',
            styleData:{
                fontSize: '40px',       // 转换为驼峰
                color: 'red',
                backgroundColor: '#ccc'
            }
        }
    }

在三木运算的时候使用

<input type="button" class="sumbitBtn" :class="isChecked == true? 'checked' : ''" value="确认">

用一个变量:isChecked,去改变 class 的name

 结合v-bind

<p class="tt_ft" v-bind:class="{'ckeck' : checkAllFlag}">全选</p>

解释:checkAllFlag 为变量,class 值为 check,checkAllFlag为 true 的时候就有 check 这个 class

 

二、v-if 和 v-show。

v-if 不会渲染dom 结构;而 v-show 是会渲染结构的;也就是说v-show 渲染的不出来的是 通过 displpay none 控制的;

  使用区别:在是否显示方面切换不是很频繁的用 v-if 相反如果切换很频繁用 v-show

(a): 单独使用

<div class="arror" v-if="item.supports.length > 2">
      {{item.supports.length}}个活动<i class="iconfont">&#xe61a;</i>
</div>

<div v-else>Now you don't</div>
<div class="wrap_wrap" :class="isShowBototm? 'Zindex': ''"></div>

(b):和 v-for 一块使用

<li class="shop_supports_item" v-for="(itemSp,index) in item.supports" v-if="index < 2">
     <span class="shop_icon_sup" :class="classMap[item.supports[index].type]"></span>
     <span class="supports_text">{{itemSp.description}}</span>
</li>

三、vue-cli 设置每个页面标题

在vue-router页面配置中添加meta的title信息,配合vue-routerbeforeEach注册一个前置守卫用户获取到页面配置的title 

const title = '移动端';
export default function getPageTitle (pageTitle) {
    if (pageTitle) {
        return `${pageTitle} - ${title}`
    }
    return `${title}`
}
router.beforeEach((to, from, next) => {
  // set page title
  document.title = getPageTitle(to.meta.title)
}

router

{
            path: '/annunciate',
            name: 'annunciate',
            component: annunciate,
            meta:{
                title: '通告广场'
            }
        },

 

四、自定义指令在 vue2 中如何写

例如实现下边的代码,index 和 title 都需要从后台获取得到

<mt-index-section index="A">
    <mt-cell title="Aaron"></mt-cell>
    <mt-cell title="Alden"></mt-cell>
    <mt-cell title="Austin"></mt-cell>
</mt-index-section>

用v-bind 绑定 并且双引号之内是不写大括号的

<mt-index-section v-bind:index="item.indentN" v-for="(item, index) in cityList">
     <mt-cell v-for="(cName, index) in item.listCountry" v-bind:title="cName"></mt-cell>
</mt-index-section>

 5、{{}} 输出

也可以在这里面执行方法,方法里面返回什么页面显示什么

<li v-for="(item,index) in dateList" :class="item.isSign =='0' ? 'activeQ': ''" 
  key="index"
> {{getDay(item.id)}}
</li>
getDay (day) {
    var arr = day.split('-');
    let dayN = arr[2];
    return dayN;
}

 6、路由中的全进后退方法

// 前进
this.$router.go(1)
// 后退
this.$router.go(-1)

7、vue 添加数据时怎么去掉input内容里面的前后空格

 <input class="ipt_travelTit" type="text" v-model.trim="title" placeholder="请输入您的游记标题" />

8、点击哪一个哪一个高亮显示

<a  v-for="(item, index) in classificaList" key="index"
    :class="selectTab === item.id? 'active': ''"
    @click="selectClassFay(item)"
> <span class="mint-cell-text">{{item.name}}</span> </a>

js中

selectClassFay (tab) {
   this.selectTab = tab.id;
}
利用  :class="selectTab === item.id? 'active': ''"
点击的时候让:selectTab 等于 item.id。
9、vue 使用循环
this.cartList.forEach((item) => {
    item.checked = this.checkAllFlag;
});

 10、数据的初始展示以及展示全部

在开发中会有这样的情况:例如 地址列表开始的时候只展示三个地址,点击展开全部展开所有的数据。方法:定义一个 过滤,用过滤去实现。

<div class="address_com_wrap" v-for="(item, index) in addressListFilter" keys="idnex">

data () {
    return {
        addressList: [],
        limit: 3
    }
},
mounted(){
    this.getAddressLists();
},
computed: {
    addressListFilter() {
        //slice 截取数组的数据,返回新的数组
        return this.addressList.slice(0, this.limit);
    }
},
created () {},
methods: {
    /**
    * 获取收货数据
    */
    getAddressLists() {
        this.$http.get('/users/addressList').then((response) => {this.addressList = response.body.result;
        });
    },
    /**
    * 获取地址(点击展示全部调用这个函数)
    */
    showMore(){
         if(this.limit == 3){
              this.limit = this.addressList.length;
        }else{
              this.limit = 3;
        }
    }
},

// addressList 为初始请求过来的不处理的数据,addressListFilter 是经过我们处理过的数据,页面循环的时候循环这个数据,在计算的属性中
,进行时时计算,limit 就是我们定义的初始展示几个数据,点击More 判断如果 limt 等于3 我们就赋值让等于初始获取的额数据的长度,这样就实现
点击展示全部再点击展示3个

 11、vue页面打开的时候有时候会闪现一下源代码

解决方案:css中

[v-cloak] {  
    display: none;  
}  

页面中

<div id="app" v-cloak>

  12、vue图片懒加载

npm install vue-lazyload --save-dev

main.js引入插件:

import VueLazyLoad from 'vue-lazyload'
Vue.use(VueLazyLoad,{
    error:'./static/error.png',
    loading:'./static/loading.png'
})

// 图片放在static中

vue文件中将需要懒加载的图片绑定 v-bind:src 修改为 v-lazy 

<img class="item-pic" v-lazy="newItem.picUrl"/>

使用 vue-lazyload 当需要动态切换图片时,DOM绑定的图片不会变

<img v-lazy="ImgSrc" :key="ImgSrc">

13、监听回车事件,实现回车登录。input事件

在密码Input上,添加登录函数

<input v-model="userPwd" placeholder="请输入密码..." type="password" @keyup.enter="login"></input>

focus事件

<input class="header-search-input" @focus="focus" type="text" placeholder="搜索商家或地点">

blur事件

<input class="header-search-input" @blur="blur" type="text" placeholder="搜索商家或地点">

实时监听有输入东西了

<input class="header-search-input" @input="search" type="text" placeholder="搜索商家或地点">

 14、vue项目基础构建

<script>
    import Header from '@/components/public/header/header'
    export default {
        name: 'mall',
        components: {
            Header
        },
        data () {
            return {
                msg: '商城首页'
            }
        },
        mounted(){
            this.init();
        },
        created () {

        },
        methods: {
            init(){
                
            }
        },
     watch:{
      
     } }
</script>

 15、页面中动态赋值路由

<li class="active" v-for="(item, index) in nav" :key="index">
        <router-link :to="{name: item.link}"> 
                {{item.name}}
        </router-link>
</li>

 16、watch监听bind绑定的值

例如: checkbox 绑定一个值 checkAll 监听选中事件。

<el-checkbox v-model="checkedAll">
      <span class="tableTop">全选</span>
</el-checkbox>

js

watch:{
      checkedAll: function toggle(){
                console.log(this.checkedAll);
       }
}

  有的时候父子组件传递值的时候,父组件的值是动态获取或者动态赋值的时候,页面刷新子组件就获取不到。通过watch 

export default {
        props: ['shopId'],
        name: 'journey',
        data () {
            return {
                initDate: []
            }
        },
        mounted(){
            // console.log(this.shopId)
        },
        watch: {
            shopId(newValue, oldValue) {
                console.log(newValue)
                this.init();
            }
        },
        mixins: [http]
    }

 17、基于webpack环境vue组件首页标题前的小图标显示问题

想要让favicon.ico 的兼容性更好,favicon.ico这个图标一般建议是放在根目录的。放在其他目录,页面加载可能获取不到 
如果是脚手架新建的话,找到你的配置文件 
// build/webpack.dev.conf.js 
new HtmlWebpackPlugin({
    filename: 'index.html',
    template: 'index.html',
    inject: true,
    favicon: './favicon.ico'   // 加上这个
})

//index.html 中

<link rel="shortcut icon" href="./favicon.ico" type="image/x-icon"/>

修改完记得 npm run dev 重启

18、vue有点时候页面很长打开并不在页面的顶部
updated() { 
     window.scroll(0, 0); 
},
19、vue路由错误跳转404或者不匹配路由跳转

 router index.js添加

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

 20、vue组织冒泡

<div class="dailog_container"
    @click="closeDailog()"
>
    <div class="dailog_wrap">
          <textarea class="area_style" placeholder="请输入评论" name="" id="" cols="30" rows="10"
                @click.stop=""
          ></textarea>
          <div class="push_word" @click.stop="pushWordFun()">发表评论</div>
     </div>
</div>

在里面使用

@click.stop

 21、switch的使用

switch(date.type){
                    case 'outCo':
                        
                        break;
                    case 'inCo':
                        
                        break;
                    case 'siCo':
                        
                        break;
                }

 22、vue路由变化后。定时器还是在执行怎么清除

data () {
       return {
             _timeOut:null
       }
},
在mounted(){}定义计时器
mounted(){
    this._timeOut = setInterval(() => {
        //  数据请求
    },2000)
},
在methods里清除计时器
methods:{
    beforeDestroy() {
        clearInterval(this._timeOut);
    }
}

 23、vue中使用 radio

定义单选时候,我们要添加统一的同一个变量名称,这个变量会保存单选的选中元素。

单选要设置value值,这里的值会保留v-model的变量属性中

<label>男<input type="radio" v-model="sex" value="man" ></label>

<label>女<input type="radio" v-model="sex" value="woman"></label>

data: {
    sex: ''   //未选中任何。为空  
    //man  默认选中man
}

 24、vue移动项目如何真机测试

正常的移动项目:localhost换成ip就可以在手机访问,但是vue的换了之后是不行的还需要,

找到config文件下面的index.js , module.exports下面dev下面的有个host,改成 ip 地址

  25、vue监听 select

<select v-model='type' @change='changeType' class='form-control'>
     <option value='radio'>单选</option><option value='checkbox'>多选</option>

vue获取当前select选中的value和text,vue的methods:

changeType: function (ele) {
    var optionTxt = $(ele.target).find("option:selected").text();
    var optionVal = ele.target.value;
  26、vue 字符串模板拼接
 <form method="post" id="" enctype="multipart/form-data" class="clearfix imgWrapUp"
                            v-for="(item, index) in image_arr" :key="index"
                        >
                            <p class="upName">{{index + 1}}、{{item.name}}</p>
                            <div class="position_picWrap">
                                <img :class="user_picNews" :id="`portrait${index+1}`" :src="picture" alt="">
                                <input type="file" class="saveImage" id="saveImage1" name="myphoto" v-on:change="handleFileUpload($event,1)">
                            </div>
                            <el-button size="small" class="leftSUre" type="primary" @click="imageSubmit(1)">点击上传</el-button>
                        </form>

 

 27、vue 动态修改状态
例如用户审核状态,包含多种状态,根据不同状态显示不同的按钮
 <el-table-column class-name="status-col" label="Status" width="110">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>

filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
28、Vue如何将图片转base64
 
<div class="pic_upLoad_wrap">
                    <i v-if="postForm.giftImageBasecode == ''" class="el-icon-plus"></i>
                    <img v-else :src="postForm.giftImageBasecode" id="portrait" alt="">
                    <input type="file" name="file" id="saveImage" @change="imageSubmit()">
                </div>

imageSubmit(){
                let file = document.getElementById('saveImage').files[0];
                var that = this;
                var reader = new FileReader();
                reader.onloadend = function () {
                    that.postForm.giftImageBasecode = reader.result
                    //这里调用了向后台发请求的代码
                }
                if (file) {
                    reader.readAsDataURL(file);
                }
            },



原文地址:https://www.cnblogs.com/haonanZhang/p/6971788.html