解決vue做詳情頁跳轉(zhuǎn)的時候使用created方法 數(shù)據(jù)不會更新問題
大家在做項目的時候肯定會遇到攜帶某個參數(shù)跳轉(zhuǎn)到詳情頁 然后取這個參數(shù),下面是重點(diǎn)
剛開始我用cookie把這個參數(shù)存起來在詳情頁面取這個參數(shù)發(fā)現(xiàn)只有第一次取到的是正確的 你在回到父頁面在點(diǎn)擊進(jìn)詳情頁發(fā)現(xiàn)取到的數(shù)據(jù)跟原來的一模一樣根本沒有發(fā)生改變(因為router跳轉(zhuǎn)時是不會刷新頁面的所以導(dǎo)致我取得值永遠(yuǎn)不能更新),我以為是cookie有問題了后來又用了query攜帶參數(shù)跳轉(zhuǎn),sessionStorage方法存取發(fā)現(xiàn)都不行,
看下圖解決辦法
我也不知道其中是什么原理 沒搞明白 但是解決了問題了,看了文檔還是沒理解這兩個方法具體區(qū)別。
補(bǔ)充知識:vue中子組件的created、mounted鉤子中獲取不到props中的值問題
父子組件通信
這個官網(wǎng)很清楚,也很簡單,父組件中使用v-bind綁定傳送,子組件使用props接收即可
例如:
父組件中
<template> <div> <head-top></head-top> <section class='data_section'> <header class='chart-title'>數(shù)據(jù)統(tǒng)計</header> <el-row :gutter='20' class='chart-head'><el-col :xs='24' :sm='12' :md='6' :lg='6'><div class='grid-content data-head blue-head'>統(tǒng)計:</div></el-col><el-col :xs='24' :sm='12' :md='6' :lg='6'><div class='grid-content data-head'>銷售數(shù)量 <span>{{number}}</span></div></el-col><el-col :xs='24' :sm='12' :md='6' :lg='6'><div class='grid-content data-head'>銷售金額 <span>{{amount}}</span></div></el-col><el-col :xs='24' :sm='12' :md='6' :lg='6'><div class='grid-content data-head'>利潤統(tǒng)計 <span>{{profits}}</span></div></el-col> </el-row> </section> <chart :chartData='chartData'></chart> </div></template><script> data(){ return {number: null,amount: null,profits: null,chartData: [10,10,10] } },</script>
子組件中
export default { props: [’chartData’]}
這種情況下,子組件的methods中想要取到props中的值,直接使用this.chartData即可
但是有寫情況下,你的chartData里面的值并不是固定的,而是動態(tài)獲取的,這種情況下,你會發(fā)現(xiàn)methods中是取不到你的chartData的,或者取到的一直是默認(rèn)值
比如下面這個情況
父組件中
<script> data(){ return {number: null,amount: null,profits: null,chartData: [] } }, mounted(){ this.getStatistics(); }, methods: { //獲取統(tǒng)計數(shù)據(jù) getStatistics(){console.log(’獲取統(tǒng)計數(shù)據(jù)’)axios.post(api,{}).then((res) => { this.number = res.data.domain.list[0].number; this.amount = res.data.domain.list[0].amount; this.profits = res.data.domain.list[0].profits; this.chartData = [this.number,this.amount,this.profits];}).catch((err) => { console.log(err);}) }, },</script>
此時子組件的methods中使用this.chartData會發(fā)現(xiàn)是不存在的(因為為空了)
這情況我是使用watch處理
解決方法如下:
使用watch
props: [’chartData’], data(){ return {cData: [] } }, watch: { chartData: function(newVal,oldVal){this.cData = newVal; //newVal即是chartDatathis.drawChart(); } },
監(jiān)聽chartData的值,當(dāng)它由空轉(zhuǎn)變時就會觸發(fā),這時候就能取到了,拿到值后要做的處理方法也需要在watch里面執(zhí)行!
以上這篇解決vue做詳情頁跳轉(zhuǎn)的時候使用created方法 數(shù)據(jù)不會更新問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
