javascript - 将 vuex 状态和突变绑定(bind)到基于 TypeScript 的 Vue 中的复选框组件属性

标签 javascript typescript vue.js vue-component vuex

问题

将复选框创建为 Vue 组件,特此:

  1. 复选框组件内不允许有任何逻辑:所有事件处理程序以及checked属性完全取决于外部逻辑,可能是 vuex商店。
  2. 我们不应该观察复选框的“选中”状态:选中与否,它再次取决于外部逻辑,例如。 G。 vuex状态或 setter/getter 。

尝试1

概念

复选框组件有 checkedonClick偏离当然值的属性可以是动态的。

组件

Pug 中的模板语言:

label.SvgCheckbox-LabelAsWrapper(:class="rootElementCssClass" @click.prevent="onClick")
  input.SvgCheckbox-InvisibleAuthenticCheckbox(
    type="checkbox"
    :checked="checked"
    :disabled="disabled"
  )
  svg(viewbox='0 0 24 24').SvgCheckbox-SvgCanvas
    path(
      v-if="!checked"
      d='M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3M19,5V19H5V5H19Z'
    ).SvgCheckbox-SvgPath.SvgCheckbox-SvgPath__Unchecked
    path(
      v-else
      d='M10,17L5,12L6.41,10.58L10,14.17L17.59,6.58L19,8M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3Z'
    ).SvgCheckbox-SvgPath.SvgCheckbox-SvgPath__Checked
  span(v-if="text").SvgCheckbox-AppendedText {{ text }}
import { Vue, Component, Prop } from 'vue-property-decorator';

@Component
export default class SimpleCheckbox extends Vue {

  @Prop({ type: Boolean, required: true }) private readonly checked!: boolean;

  @Prop({ type: Boolean, default: false }) private readonly disabled!: boolean;

  @Prop({ type: String }) private readonly text?: string;
  @Prop({ type: String }) private readonly parentElementCssClass?: string;

  @Prop({ type: Function, default: () => {} }) private readonly onClick!: () => void;
}

商店模块

import { VuexModule, Module, Mutation } from "vuex-module-decorators";
import store, { StoreModuleNames } from "@Store/Store";


@Module({ name: StoreModuleNames.example, store, dynamic: true, namespaced: true })
export default class ExampleStoreModule extends VuexModule {

  private _doNotPreProcessMarkupEntryPointsFlag: boolean = true;

  public get doNotPreProcessMarkupEntryPointsFlag(): boolean {
    return this._doNotPreProcessMarkupEntryPointsFlag;
  }

  @Mutation
  public toggleDoNotPreProcessMarkupEntryPointsFlag(): void {
    this._doNotPreProcessMarkupEntryPointsFlag = !this._doNotPreProcessMarkupEntryPointsFlag;
  }
}

用法

SimpleCheckbox(
  :checked="relatedStoreModule.doNotPreProcessMarkupEntryPointsFlag"
  :onClick="relatedStoreModule.toggleDoNotPreProcessMarkupEntryPointsFlag"
  parentElementCssClass="RegularCheckbox"
)
import { Component, Vue } from "vue-property-decorator";
import { getModule } from "vuex-module-decorators";
import ExampleStoreModule from "@Store/modules/ExampleStoreModule";
import template from "@Templates/ExampleTemplate.pug";
import SimpleCheckbox from "@Components/Checkboxes/MaterialDesign/SimpleCheckbox.vue";

@Component({ components: { SimpleCheckbox } })
export default class MarkupPreProcessingSettings extends Vue {
  private readonly relatedStoreModule: ExampleStoreModule = getModule(ExampleStoreModule);
}

华林斯

如果点击复选框出现。 Checkbox 可以按我们的需要工作,但是违反了一些 Vue 概念。

enter image description here

vue.common.dev.js:630 [Vue warn]: $attrs is readonly.

found in

---> <SimpleCheckbox> at hikari-frontend/UiComponents/Checkboxes/MaterialDesign/SimpleCheckbox.vue
       <MarkupPreProcessingSettings>
         <Application> at ProjectInitializer/ElectronRendererProcess/RootComponent.vue
           <Root>

vue.common.dev.js:630 [Vue warn]: $listeners is readonly.

found in

---> <SimpleCheckbox> at hikari-frontend/UiComponents/Checkboxes/MaterialDesign/SimpleCheckbox.vue
       <MarkupPreProcessingSettings>
         <Application> at ProjectInitializer/ElectronRendererProcess/RootComponent.vue
           <Root>

vue.common.dev.js:630 [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "checked"

found in

---> <SimpleCheckbox> at hikari-frontend/UiComponents/Checkboxes/MaterialDesign/SimpleCheckbox.vue
       <MarkupPreProcessingSettings>
         <Application> at ProjectInitializer/ElectronRendererProcess/RootComponent.vue
           <Root>

沉思

此警告经常发出,原因是某些 vue-property 的新值已在组件内部分配。明确地说,我没有进行这样的操作。

问题出在:onClick="relatedStoreModule.toggleDoNotPreProcessMarkupEntryPointsFlag" .看起来它编译成类似 <component>.$props.onClick="<vuex store manipulations ...>" 的东西- 如果是这样,则它是组件内部的隐式属性突变。

尝试2

概念

基于 Vue documentation, Customizing Component section :

Vue.component('base-checkbox', {
  model: {
    prop: 'checked',
    event: 'change'
  },
  props: {
    checked: Boolean
  },
  template: `
    <input
      type="checkbox"
      v-bind:checked="checked"
      v-on:change="$emit('change', $event.target.checked)"
    >
  `
})

vue-property-decorator 对应的 TypeScript将是:

import { Vue, Component, Model } from 'vue-property-decorator'

@Component
export default class YourComponent extends Vue {
  @Model('change', { type: Boolean }) readonly checked!: boolean
}

组件

label.SvgCheckbox-LabelAsWrapper(:class="rootElementCssClass")
  input.SvgCheckbox-InvisibleAuthenticCheckbox(
    type="checkbox"
    :checked="checked"
    :disabled="disabled"
    @change="$emit('change', $event.target.checked)"
  )
  svg(viewbox='0 0 24 24').SvgCheckbox-SvgCanvas
    // ...
import { Vue, Component, Prop, Model } from "vue-property-decorator";

@Component
export default class SimpleCheckbox extends Vue {

  @Model('change', { type: Boolean }) readonly checked!: boolean;

  @Prop({ type: Boolean, default: false }) private readonly disabled!: boolean;

  @Prop({ type: String }) private readonly text?: string;
  @Prop({ type: String }) private readonly rootElementCssClass?: string;
}

用法

SimpleCheckbox(
  v-model="doNotPreProcessMarkupEntryPointsFlag"
  rootElementCssClass="RegularCheckbox"
)

在 TypeScript 中,使用 v-model ,我们需要声明 getter 和同名的 setter:

@Component({
  template,
  components: {
    SimpleCheckbox,
    // ...
  }
})
export default class MarkupPreProcessingSettings extends Vue {

  private readonly relatedStoreModule: MarkupPreProcessingSettingsStoreModule =
      getModule(MarkupPreProcessingSettingsStoreModule);
  //...
  private get doNotPreProcessMarkupEntryPointsFlag(): boolean {
    return this.relatedStoreModule.doNotPreProcessMarkupEntryPointsFlag;
  }

  private set doNotPreProcessMarkupEntryPointsFlag(_newValue: boolean) {
    this.relatedStoreModule.toggleDoNotPreProcessMarkupEntryPointsFlag();
  }
}

警告

相同的错误集:

enter image description here

限制

首先,我们需要在 Vue 组件类中创建新的 getter 和 setter。如果可能的话,避免 id 会很酷。不幸的是,对于 vuex 类(通过 vuex-module-decorators ),TypeScript setter 不可用,我们需要使用 @Mutation -decorated 方法。

此外,此解决方案不适用于 v-for 呈现的元素.它使这个解决方案毫无用处。

尝试3

概念

事件发射器和自定义事件监听器的使用。此解决方案也可以正常工作,但 Vue 会发出警告。

组件

label.SvgCheckbox-LabelAsWrapper(:class="rootElementCssClass" @click.prevent="$emit('toggled')")
  // ...

用法

SimpleCheckbox(
  :checked="relatedStoreModule.doNotPreProcessMarkupEntryPointsFlag"
  @toggled="relatedStoreModule.toggleDoNotPreProcessMarkupEntryPointsFlag"
  rootElementCssClass="RegularCheckbox"
)

警告

enter image description here


更新

还有一些谜题,不过问题已经解决了。请参阅下面我的回答。

最佳答案

这个警告发生在 Electron 应用程序中。 SimpleCheckbox 来自 node_modules,但是该库仍在开发中,因此它已由 npm link 提供。

当我尝试复制时,我为浏览器创建了 SPA,并将 SimpleCheckbox 放置到同一个项目(不是从 node_modules 获取)。第一个解决方案有效! (我不关心第二个和第三个 - 我只需要从 peel elegant 解决方案中提炼)。

我建议原因是 npm link,发布我的库并通过 npm install 安装它。警告消失了!

结论

npm link 引起这样的问题已经不是第一次了。这是 another case .

我仍然没有深入了解这个案例——我只是发布了一些实验数据。 “那么,如果图书馆还在开发中呢?”问题仍然没有答案。我试过 Lerna - 第一次警告消失了,但是当我将我的项目移至 Lerna 时,警告再次出现 - 我还不清楚规律性。

关于javascript - 将 vuex 状态和突变绑定(bind)到基于 TypeScript 的 Vue 中的复选框组件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58110755/

相关文章:

javascript - Vuejs : Include local javascript file with &lt;script&gt; tag

javascript - 无法在 'replaceState' 上执行 'History' <local_URL> 无法在源为 'null' 的文档中创建

javascript - 有没有一种好方法可以跨事件发射器/事件循环边界显示生产中的错误痕迹?

vue.js - Vue 插件 - Vue 已定义但从未使用

javascript - 何时在 TS 中使用类型(与接口(interface))

typescript - 如何声明属性名称是数组中的值的 TypeScript 接口(interface)

javascript - 将结果与 vue.js 中更改的值同步

javascript - 事件监听器无法一致地工作 Javascript

javascript - 在 Django 模板中执行 Javascript 和 css

javascript - 是否可以在 typescript 中创建一个命名为 "fat-arrow"的 lambda?