我尝试遵循此答案this answer,但使用模块(每个组件App.vue和vue分隔的文件)
但仍然无法正常工作。
我需要制作一棵具有类似数组的树,就像用心的帖子来渲染带有链接的表,因此,首先,我尝试通过本文中的复制代码来制作一棵简单的树,但是出现了这个错误。
[Vue警告]:“数据”选项应该是一个在组件定义中返回每个实例值的函数。
我的文件:
main.js:
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: function (h) { return h(App) },
}).$mount('#app')
App.vue:
<template>
<ul id="demo">
<item class="item" :model="nestedInformation[1]"> </item>
</ul>
</template>
<script>
var data2 = [
{
id: 1,
name: "root",
parentid: null,
},
{
id: 2,
name: "movies",
parentid: 1,
},
{
name: "iron-man",
id: 3,
parentid: 1,
},
{
id: 4,
name: "iron-woman",
parentid: 2,
},
];
import Vue from "./components/myTree";
export default {
computed: {
nestedInformation: function () {
return this.nestInformation(data2);
},
},
data: {
treeData2: data2,
},
methods: {
nestInformation: function (arr, parent) {
var out = [];
for (var i in arr) {
if (arr[i].parentid == parent) {
var children = this.nestInformation(arr, arr[i].id);
if (children.length) {
Vue.set(arr[i], "children", children);
}
out.push(arr[i]);
}
}
return out;
},
},
};
</script>
myTree.vue:
<template>
<li>
<div
:class="{ bold: isFolder }"
@click="toggle"
@dblclick="changeType">
{{ model.name }}
<span v-if="isFolder">[{{ open ? '-' : '+' }}]</span>
</div>
<ul
v-if="isFolder"
v-show="open">
<item
class="item"
v-for="(model, index) in model.children"
:key="index"
:model="model"></item>
<li class="add" @click="addChild">+</li>
</ul>
</li>
</template>
<script>
import Vue from "./myTree"
export default {
computed: {
isFolder: function () {
return this.model.children &&
this.model.children.length;
}
},
data: function () {
return {
open: true
};
},
methods: {
addChild: function () {
this.model.children.push({
name: 'My Tres',
children: [
{ name: 'hello' },
{ name: 'wat' }
]
});
},
changeType: function () {
if (!this.isFolder) {
Vue.set(this.model, 'children', [])
this.addChild()
this.open = true
}
},
toggle: function () {
if (this.isFolder) {
this.open = !this.open
}
}
},
props: {
model: Object
},
};
</script>