Vue初學跳坑


1. uncaught TypeError: Cannot read property '0' of undefined

<div class="home-module-wrap">
    <image-preview :src="modules[0][0]['list'][0]['image']"></image-preview> 
    <div class="swiper-wrap-info" style="height:346px">
        <swiper-container :items="modules[0][1]['list']"></swiper-container>
    </div>
</div>
data: {
    modules: ""
},
created() {
    axios.get('/api/???').then( data => {
        this.modules = data.modules
    })
}

這分別是我的html代碼和js代碼,不知道你的代碼是否和我相似,解決這個問題的方法是在圖一的html中第一行加入v-if="modules"即可。原因是第一次渲染界面的時候module為'',去拿module['0']當然會拋出異常,我們在這之前驗證一下就行了。

2. 操作v-for生成的DOM元素

假設你用ajax從后台拿到數據,用v-for展示在前台,現在需要操作v-for生成的第二行的元素你會怎么做?你是否碰到了操作不了的錯誤。

或者和我的需求一樣,從后來拿來幾張圖片,用js插件Swiper生成一個圖片輪播的banner,你會怎么做?你是否碰到了Swiper里只有1到2張圖片,而且沒有圖片的分頁,也無法滑動。

解決辦法:

<div class="swiper-container banner">
    <div class="swiper-wrapper">
        <a v-for="banner in banners" :key="banner.id" class="swiper-slide" v-bind:href="banner.link">
            <img class="banner-img" :src="banner.image | addDomain" alt="">
        </a>
    </div>
    <div class="swiper-pagination"></div>
</div>

 

axios.get('/api/???').then( data => {
    this.banners = data.banner
    this.$nextTick( () =>
        new Swiper('.banner', {
            autoplay: 3000,
            loop: true,
            lazyLoading : true,
            autoplayDisableOnInteraction: false,
            pagination: '.swiper-pagination'
        })
    )
})

這是我swiper的代碼,把swiper的初始話放在數值改變后,this.$nextTick中就行,因為這時banners的值已經改變了

3. Uncaught SyntaxError: Unexpected token import / 

Uncaught SyntaxError: Unexpected token export

這是webpack和es6中可能會遇到的問題,出現這個問題是webpack配置的問題

解決辦法,首先webpack中關於babel的配置改為

{
      test: /\.js$/,
      loader: 'babel',
      exclude: /node_modules/
}

並在同級目錄下增加.babelrc文件,並在這個文件中寫入

{
"presets": ["es2015"],
"plugins": ["transform-runtime"],
"comments": false
}

即可。

 

如果有問題,請給我留言!


免責聲明!

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



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