问题
i've developing electron apps with vue-cli-plugin. when print an array it's return observer.
what i do:
console.log(this.listfile)
output from developer tools
[__ob__: Observer]
0: {__ob__: Observer}
1: {__ob__: Observer}
2: {__ob__: Observer}
3: {__ob__: Observer}
4: {__ob__: Observer}
5: {__ob__: Observer}
6: {__ob__: Observer}
7: {__ob__: Observer}
8: {__ob__: Observer}
9: {__ob__: Observer}
10: {__ob__: Observer}
11: {__ob__: Observer}
12: {__ob__: Observer}
13: {__ob__: Observer}
14: {__ob__: Observer}
15: {__ob__: Observer}
16: {__ob__: Observer}
length: 17
__ob__: Observer {value: Array(17), dep: Dep, vmCount: 0}
__proto__: Array
how to get this: length: 17
?
[update]
more code
data () {
return {
listfile: [],
isActive: false,
isDataExist: false
}
},
watch: {
listData: function () {
//electron filesystem
const fs = require('fs')
var dirLocation = this.listData.replace(/\\/g, "/")
console.log(dirLocation)
fs.readdir(dirLocation, (err, file) => {
file.forEach( (filename) => {
this.listfile.push({name: filename, selected: false})
})
})
console.log(this.listfile.length)
// this.isDataExist = true;
// Object.assign(this.$data, getInitialData());
},
deep: true
},
listfile is an array, initiated inside data(){}
then data from filesystem(fs) inserted to listfile
with push()
i've trying code:
console.log(JSON.stringify(this.listfile))
and only return []
回答1:
readdir is async this means you have no guarantee when it gets executed.
watch: {
listData: function () {
// electron filesystem
const fs = require('fs')
var dirLocation = this.listData.replace(/\\/g, "/")
console.log(dirLocation)
fs.readdir(dirLocation, (err, file) => {
file.forEach((filename) => {
this.listfile.push({name: filename, selected: false})
});
console.log(this.listfile.length); // works
});
// This line is executed before `file.forEach()`
},
readdirSync is the syncronous alternative.
watch: {
listData: function () {
// electron filesystem
const fs = require('fs')
var dirLocation = this.listData.replace(/\\/g, "/")
console.log(dirLocation)
var file = fs.readdirSync(dirLocation);
file.forEach((filename) => {
this.listfile.push({name: filename, selected: false})
});
console.log(this.listfile.length); // executed after the above code has run
},
来源:https://stackoverflow.com/questions/63563087/get-length-value-from-vue-observer