【发布时间】:2018-02-03 20:18:49
【问题描述】:
Vue.js 版本 2,带有单文件组件和 vue-router(和 webpack,但在这里不应该很重要)。
我已经对此进行了研究,并且我相信我可以并且似乎无法解开一个在渲染组件时填充和渲染对象的良好模式,希望解决方案对某人来说是显而易见的,并且很容易解释。
Main.js(从 webpack.base.config 调用):
var vm = new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
App.vue:
<template>
<router-view></router-view>
</template>
<script>
export default {
name: 'app'
}
</script>
Child.vue(重要的是要注意我在这里所做的是 1)进行 api 调用(通过 javascript 承诺)2)迭代响应并填充 temp Object @ 987654325@ 具有每个重要位的键和值的属性,然后 3) 触发computed.cObj.set() 以呈现列表):
<template>
<div class="child">
<ul>
<li v-for="i in cObj">{{ i }}</li>
</ul>
</div>
</template>
<script>
export default {
name: 'child',
data () {
return {
obj: {}
}
},
computed: {
cObj: {
get: function () {
return this.obj
},
set: function (nv) {
this.obj= nv
}
},
// cObj: function () {
// return this.getAll()
// }
},
created () {
let conditional = true
if (!conditional) // ...do something else
else this.getAllX()
},
methods: {
getAll: function () {
let x = {} // temporary object
// in this promise I'm returning data from the server
server.getData()
.then(function (r) {
// iterate response
r.records[0].operations().then(r => {
for (let a in r) {
if (typeof r[a].records === 'object') {
for (let b in r[a].records) {
Object.keys(r[a].records[b]).forEach(function (key) {
if (r[a].records[b][key] !== undefined) {
// add key/value to x
x[key] = r[a].records[b][key]
}
})
}
}
}
})
})
.catch(function (err) {
console.log(err)
})
this.cObj = x // THIS IS WHAT IS KILLING ME HERE, I must be misunderstanding the documentation here because the computed `set` method isn't triggered or I'm misunderstanding vue lifecycle, I thought calling the computed.cObj.set() should trigger the rendering of the list but it does not.
// return x | tried this as well (see commented out computed.cObj)
}
}
}
</script>
查看控制台中填充的对象,我得到以下信息,但未呈现列表:
// {}
// detailOne: "asdf"
// detailTwo: "asdf asdf"
// __proto__: Object { … }
这是一个类似的问题Vue.js : How to make dynamic menu?
【问题讨论】:
-
为什么需要一个计算属性?您可以将
cObj初始化为数据,然后像this.cObj = x;那样简单地设置它 -
谢谢,我会试一试。如果我错了,请纠正我,如果我理解正确你说我应该设置
this.data = x。编辑:我相信你的意思是把计算出的cObj移到数据中,试试看。 -
不。我会给你一个更完整的样本。等一下:)
-
是的,将
cObj移至数据 :) -
好的,谢谢...测试。编辑:无赖!也没有用。与之前一样,填充了
cObj(每个控制台输出),但在填充对象后组件不会呈现数据:/.
标签: javascript ajax vuejs2