[英]VueJS Adding data from query parameters
我正在開發一個小型純客戶端 VueJS 應用程序,該應用程序使用VueRouter
在將數據輸入應用程序時更新 URL,因此用戶可以使用 URL 刷新頁面並在刷新頁面時將數據重新加載到應用程序中。 數據存儲在查詢參數中,例如:
.../app.html#/?time=300&time=300&distance=300&distance=300&unit=m&unit=m
router
根據需要解析數據,但是當我將數據添加到我的空performance
數組時,我的標記中的:class
屬性會引發
TypeError:無法讀取未定義的屬性“長度”
其中undefined
是performances
數組。 我通過從應用程序的標記中刪除:class
並成功呈現了站點,將這個問題縮小到v-for
性能循環內的:class
屬性。 我猜performances
數據數組尚未傳遞給:class
。
我在VueRouter文檔中沒有看到任何提及這種類型的路由。 應該如何將數據從 URL 查詢參數傳遞到應用程序? 這是我的相關代碼(為簡潔起見進行了精簡):
// js file
var router = new VueRouter({}); // empty because no routes, just query parameters, so no need for list
var app = new Vue({
el: '#app',
data: function() {
return {
performances: [],
units: units,
newPerformance: {
distance: {
value: '',
units: units.distance.options[0]
},
time: {
formatted: '',
value: ''
},
},
editingPerformance: null,
}
},
router: router,
watch: {
performances: {
handler: function() {
this.drawChart();
this.updateURL();
},
deep: true
}
},
updateURL: function() {
var times = this.performances.map(function(v) {
return v.time.value
}),
distances = this.performances.map(function(v) {
return v.distance.value
}),
units = this.performances.map(function(v) {
return v.distance.units.value
});
router.push({
query: {
time: times,
distance: distances,
dunit: units
}
});
}
....
});
HTML 文件
...
<div v-for="(performance, index) in performances" :class="{'card-list': performances.length > 1 }">
...
</div>
...
我已閱讀Reactivity in Depth文檔並嘗試了以下解決方案:
Vue.nextTick(function() {
this.performances.push(performance);
})
和
Vue.set(app, 'performances',performanceArray);
導致相同的錯誤。 我可以根據要求提供更多代碼。
編輯:添加堆棧跟蹤:
[Vue warn]: Error when rendering root instance: warn @ vue.js:513
Vue._render @ vue.js:2934
(anonymous function) @ vue.js:2335
get @ vue.js:1643run @ vue.js:1712
flushSchedulerQueue @ vue.js:1530
(anonymous function) @ vue.js:465
nextTickHandler @ vue.js:414
緊隨其后的是:
vue.js:427 TypeError: Cannot read property 'length' of undefined(…)
logError @ vue.js:427
似乎您可能將其設置為代碼中某處的數組以外的其他內容。 您將其實例化為一個數組,而 .length 僅適用於數組和字符串,因此如果將其設置為對象、json 或其他任何內容,它將出錯。 Vue.nextTick 有一個回調,除非你將它設置為與 Vue.nextTick 函數相同范圍內的變量,否則它不會攜帶“this”。 就像是
var self = this;
//inside nextTick
self.performances.push(performance);
但我想你不應該使用 nextTick 因為在重新渲染 DOM 后 nextTick 會更新。 push() 函數將觸發 dom 重新渲染,這將使您的頁面響應。 如果您等待 nextTick 那么它可能永遠不會更新,直到您更改其他內容。
<div v-if="performances.length" v-for="(performance, index) in performances"
:class="performances.length > 1 ? 'card-list' : ''">
...
</div>
v-if 屬性將確保在內容存在之前它不會呈現。
那應該可以解決您的問題
您還可以執行 {{ performance }} 來找出對象中的確切內容,並且 Google chrome 有一個 vue-debugger 擴展。 它向您展示了所有數據屬性的實時模型。 我會推薦使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.