我正在使用Vue3和API组合。我已经设置了一个存储(不使用VUEX(来存储全局设置。我有一个侧边栏,我想扩展或折叠。我首先把所有的代码放在一个组件中,发送给父级来展开或折叠侧边栏,效果很好。然后,我尝试重构以使用存储来在视图中设置侧边栏,但emit在第二个版本中不起作用。
如果不使用存储,则所有代码都是组件的本地代码。它非常有效,并将价值传递给父对象。
//regular
import { ref } from "vue";
export default {
name: "rightmenu",
emits: ["showRightMenu"],
props: ["bgcolor"],
setup(props, context) {
const showRightMenu = ref(true);
function toggleRightMenu() {
if (showRightMenu.value == false) {
showRightMenu.value = true;
} else {
showRightMenu.value = false;
}
context.emit("showRightMenu", showRightMenu.value);
}
return { showRightMenu, toggleRightMenu };
},
};
以下使用存储来更新项和运行方法。
//with store
import { ref, inject } from "vue";
export default {
name: "rightmenu",
emits: ["showRightMenu"],
props: ["bgcolor"],
setup(context) {
const store = inject("store");
const showRightMenu = ref(store.showRightMenu);
function toggleRightMenu() {
const aValue = store.methods.toggleRightMenu();
context.emit("showRightMenu", aValue); //ISSUE
}
return { showRightMenu, toggleRightMenu };
},
};
我得到以下错误:
未捕获类型错误:context.emit不是函数在Proxy.toggleRightMenu
这是商店代码:
import { ref } from "vue";
const showRightMenu = ref(true);
const methods = {
changeColor(val) {
state_color.color = val.color;
state_color.colorName = val.title;
},
toggleRightMenu() {
if (showRightMenu.value == false) {
showRightMenu.value = true;
} else {
showRightMenu.value = false;
}
return showRightMenu.value
},
};
const getters = {};
export default {
showRightMenu,
methods,
getters,
};
您的设置函数似乎不正确。
在第一个例子中,您使用props作为第一个参数,但在第二个例子中没有。
setup(props, context) {
作品
setup(context) {
没有,因为context
arg实际上是由props
而不是context
填充的