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)迭代响应并填充临时{{1} } Object
属性,每个重要位的键和值,然后3)触发let x = {}
以便呈现列表):
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>
答案 0 :(得分:1)
在 Child.vue :
中尝试此操作阵列方式:
<template>
<div>
<ul>
<li v-for="(item, index) in cObj" :key="index">{{ item.name }}</li>
</ul>
</div>
</template>
<script>
export default {
data () {
return {
cObj: {}
}
},
created () {
let conditional = true
if (!conditional) {
}
else {
this.getAll()
}
},
methods: {
getAll: function () {
let x = [
{ id: 1, name: 'one' },
{ id: 2, name: 'two' },
{ id: 3, name: 'thre' },
]
this.cObj = x;
}
}
}
</script>
对象方式:
<template>
<div>
<ul>
<li v-for="(value, key) in cObj" :key="key">{{ key }} : {{ value.name }}</li>
</ul>
</div>
</template>
<script>
export default {
data () {
return {
cObj: {}
}
},
created () {
let conditional = true
if (!conditional) {
}
else {
this.getAll()
}
},
methods: {
getAll: function () {
let x = {
first: { id: 1, name: 'one' },
second: { id: 2, name: 'two' },
third: { id: 3, name: 'three' },
};
this.cObj = x;
}
}
}
</script>