近期用Vue.js搭了一個(gè)仿cnode的社區(qū),中間遇到一些坑,故把一些注意事項(xiàng)記錄下來。
預(yù)覽鏈接:https://yukiweng.github.io/cnode/dist/index.html
將整個(gè)項(xiàng)目結(jié)構(gòu)拆分為以下組件:
- header 頭部
- PosList 文章列表
- Article 文章詳情頁
- SlideBar 側(cè)邊欄
- UserInfo 用戶信息
- Pagination 分頁
請求數(shù)據(jù)相關(guān)
- 使用axios發(fā)請求,項(xiàng)目安裝axios
全局注冊在Vue原型上
Vue.prototype.$http=axios
//發(fā)請求帶參數(shù)時(shí),需用params:{}包裹起來
this.$http.get('/',{params:{}})
實(shí)例加載完成前請求數(shù)據(jù) beforeMount
頁面渲染時(shí),某些元素需要?jiǎng)討B(tài)綁定,如 <img :src="..."> ,否則獲取不到更新的數(shù)據(jù)報(bào)錯(cuò):
Cannot read property 'loginname' of undefined
異步請求獲取數(shù)據(jù)時(shí),由于數(shù)據(jù)時(shí)異步獲取的,所以一開始是沒有該數(shù)據(jù)屬性的
我將獲取的數(shù)據(jù)放入一個(gè)對象dataList,里面的數(shù)據(jù)類似{author:{avatar_url:"",logginame:""}}
在這個(gè)數(shù)據(jù)中,由于初始值dataList.author是一個(gè)空對象(undefined),
author.loginname相當(dāng)于undefined.loginname,故報(bào)錯(cuò)。
(后來異步請求拿到數(shù)據(jù)就渲染了,頁面看著是正常的,但控制臺的報(bào)錯(cuò)會影響之后的操作)
解決方法兩種:
① 在標(biāo)簽上加 v-if="dataList.author"
② 在數(shù)據(jù)未加載完成前,整個(gè)頁面只渲染一個(gè)loading.gif
路由跳轉(zhuǎn)
- 路由跳轉(zhuǎn)傳遞多個(gè)參數(shù),用 & 拼接,如
path:'/topic/:id&author=:name'
// /:第一個(gè)參數(shù)&自定義變量名=:第二個(gè)參數(shù)
// 配置路由
name: 'article',
path: '/topic/:id&author=:name',
components: {
main: Article,
slideBar: SlideBar
}
// A組件中跳轉(zhuǎn)
<router-link :to="{name:'article',params:{id:item.id,name:item.author.loginname}}">
</router-link>
// B組件獲取參數(shù)
this.$route.params.id
this.$route.params.name
- 假如要跳轉(zhuǎn)的路由和當(dāng)前路由是同一個(gè),
雖然傳遞的參數(shù)不一樣,但瀏覽器默認(rèn)為同一路由,頁面不會重新渲染。
此時(shí),可用watch方法:觀察Vue實(shí)例上的數(shù)據(jù)變動,只要指定的數(shù)據(jù)改變就會執(zhí)行預(yù)定的函數(shù)。
// 監(jiān)視 $route ,接的參數(shù)為新值和舊值,當(dāng)值發(fā)生改變(自動檢測),執(zhí)行里面的方法
watch:{
$route:function(to,from){
this.getData()
}
}
其他
過濾器的代碼順序:
main.js中,我原本先寫Vue實(shí)例,再寫過濾器,
結(jié)果,在子組件中,第一次加載OK,但頁面刷新就報(bào)錯(cuò):
[Vue warn]: Failed to resolve filter: formatDate
解決方法:
應(yīng)該先全局注冊過濾器,寫在上面,再寫vue實(shí)例
Vue.filter()
new Vue()上傳github,因路徑問題無法預(yù)覽
解決方法:
// 先打包
npm run build // 自動創(chuàng)建dist文件夾
// config 路徑下的index.js ,修改build配置
// assetsPublicPath: '/' 絕對路徑改相對路徑
assetsPublicPath: './'
// productionSourceMap:true 改為
productionSourceMap: false