Vue 将输入规则的箭头函数传递给 Stancil 组件

问题描述

我正在尝试传递箭头函数,该函数将用作 Vuetify https://vuetifyjs.com/en/api/v-input/#rules 中的输入规则。所以我用代码在数组中传递规则:

<body>
    <div id="app">
      <test-component :rules="[required,passwordRule]" :placeholder="placeholder" :label="label" :value="value" @valueChange="e => onValueChange"></test-component>
      {{value}}
      <button @click="value = 'test'">Test</button>
    </div>
  </body>
  <script>
    var app = new Vue({
      el: '#app',data() {
        return {
          label: 'Username',value: '',placeholder: 'Write username',required: v => !!v || 'This field is required',passwordRule: v => v.length >= 8 || 'Your password is too short',};
      },methods: {
        onValueChange(e) {
          console.log(e);
        },},});
  </script>

然后我想通过观察者在带有控制台日志的 Stencil 组件中检查它,但它返回未定义:

  @Prop() rules: Array<Function>;
  @Watch('value')
  watchHandler(newValue: string,oldValue: string) {
    console.log(this.rules);
    /* ... */
  }

解决方法

当你想传递一个可以是数组或对象的规则道具时,你需要将它作为 :rules.prop="[array]"

在你的情况下,它应该是这样的

<test-component :rules.prop="[required,passwordRule]" :placeholder="placeholder" :label="label" :value="value" @valueChange="e => onValueChange"></test-component>