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]
    }
  },

 


 

 

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM