【问题标题】:Vue3 Composition API emit works without store but not with storeVue3 Composition API 发出没有商店但没有商店的作品
【发布时间】:2022-01-18 01:10:27
【问题描述】:

我正在使用 Vue3 和组合 API。我已经建立了一个商店(不使用 VUEX)来存储全局设置。我有一个要展开或折叠的侧边栏。我首先将所有代码放在一个组件中以发送给父级以展开或折叠侧边栏,效果很好。然后我尝试重构以使用商店在视图中设置侧边栏,但在第二个版本中发出将不起作用。

不使用商店,所有代码都是组件的本地代码。它工作得很好,并向父级发出值。

//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 };
  },
};

下面使用store更新item和run方法。

//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,
};

【问题讨论】:

    标签: vuejs3 vue-composition-api


    【解决方案1】:

    您的设置功能似乎不正确。

    在第一个示例中,您使用道具作为第一个参数,但在第二个示例中没有。

    setup(props, context) { 有效

    setup(context) { 不是因为 context 参数实际上是由 props 而不是 context 填充的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      • 2016-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多