axios - 在ajax方法之后在vue 3中渲染菜单
问题描述
我已经让这个菜单在没有过滤的情况下工作,但现在我正在做一个 ajax 请求来过滤掉用户不应该看到的菜单项,我在弄清楚如何设置结果时遇到了一些麻烦菜单数据,不工作的行在下面注释:
<script>
import { ref } from 'vue';
import axios from 'axios';
var currentSelected = 'device_access';
var menuData = [
{
text: 'Device Access',
id: 'device_access',
children: [
{
text: 'Interactive',
link: '/connection_center'
},{
text: 'Reservation',
link: '/reserve_probe'
}, {
text: 'Reservation Vue',
link: '/reservation.html'
}
]
}, {
text: 'Automation',
id: 'automation',
show: ['is_mxadmin', 'can_schedule_scripts'],
children: [
{
text: 'Builder',
link: '/builder',
},{
text: 'Execution Results',
link: '/test_suite_execution_results'
},
]
}
];
function hasMatch(props, list) {
var match = false;
for (var i=0; i < list.length && !match; i++) {
match = props[list[i]];
}
return match;
}
export default {
name: 'Header',
setup() {
const cursorPosition = ref('0px');
const cursorWidth = ref('0px');
const cursorVisible = ref('visible');
//the menu is zero length until I get the data:
const menu = ref([]);
return {
menu,
cursorPosition,
cursorWidth,
cursorVisible
}
},
created() {
let that = this;
axios.get('navigation_props')
.then(function(res) {
var data = res.data;
var result = [];
menuData.forEach(function(item) {
if (!item.show || hasMatch(data, item.show)) {
var children = [];
item.children.forEach(function (child) {
if (!child.show || hasMatch(data, child.show)) {
children.push({ text: child.text, link: child.link });
}
});
if (children.length > 0) {
result.push({ text: item.text,
children: children, lengthClass: "length_" + children.length });
}
}
});
//continues after comment
这可能是唯一的错误,我已经在调试器中运行了它并且我得到了正确的数据:
that.$refs.menu = result;
由于没有重建菜单,因此失败:
//this.restoreCursor();
})
.catch(error => {
console.log(error)
// Manage errors if found any
});
},
解决方案
this.$refs
用于模板 refs,与ref
s from不同setup()
。
并且获取的数据created()
可能应该移动到onMounted()
in setup()
,其中axios.get()
回调设置menu.value
了结果:
import { onMounted, ref } from 'vue'
export default {
setup() {
const menu = ref([])
onMounted(() => {
axios.get(/*...*/).then(res => {
const results = /* massage res.data */
menu.value = results
})
})
return {
menu
}
}
}