【问题标题】:How to extend the behaviour of components in VueVue中如何扩展组件的行为
【发布时间】:2019-10-05 13:42:48
【问题描述】:

我主要有 React 方面的经验,我想知道以 Vue 为中心的做法是什么:

我想扩展这个组件:https://element.eleme.io/#/en-US/component/form,这样label-position 在移动设备上是top,在桌面设备上是left。我不确定如何将传递给组件的属性传播到元素上。

这是我目前的伪代码:

<template>
  <el-form v-bind="formProps" :label-position="labelPosition">
    <slot />
  </el-form>
</template>

<script>
import Vue from 'vue';

export default Vue.component('el-form-responsive', {
  data() {
    return {
      labelPosition: 'top',
    };
  },
  created() {
    this.mobileQuery = window.matchMedia('(max-width: 720px)');
    this.onMobileQueryTrigger(this.mobileQuery);
    this.mobileQuery.addListener(this.onMobileQueryTrigger);
  },
  beforeDestroy() {
    this.mobileQuery.removeListener(this.onMobileQueryTrigger);
  },
  methods: {
    onMobileQueryTrigger(query) {
      if (query.matches) {
        console.log('is mobile');
        this.$data.labelPosition = 'top';
      } else {
        this.$data.labelPosition = 'left';
        console.log('is not mobile');
      }
    },
  },
});
</script>

据我了解v-binddoes not copy over events and directives,所以这不起作用:

<el-form-responsive
  :formProps="{
    class: 'form',
    ':model': 'formValues',
    'status-icon': true,
    ':rules': 'rules',
    ref: 'form',
    'label-width': 'auto',
    '@submit.native.prevent': 'submitForm'
  }"
>

又不方便又丑陋,我宁愿这样做:

<el-form-responsive
  class="form"
  :model="formValues"
  status-icon
  :rules="rules"
  ref="form"
  label-width="auto"
  @submit.native.prevent="submitForm"
>

但我不确定如何将这些道具传播到el-form?这不是以 Vue 为中心的方式吗?似乎是一个基本的东西,所以也许我错了。

【问题讨论】:

  • vuejs.org/v2/api/#vm-listeners。类似v-bind="$props" v-on="$listeners". You'd also need to copy across the props` 的定义来自其他组件,或者使用$attrs 而不是$props。在此示例中,扩展而不是组合可能更简单。

标签: javascript vue.js


【解决方案1】:

我现在无法对此进行测试,但我相信 $attrs$listeners 应该做你想做的事情,或者至少为你指明正确的方向:

<template>
  <el-form v-bind="$attrs" v-on="$listeners" :label-position="labelPosition">
    <slot />
  </el-form>
</template>

【讨论】:

  • 很好,我很高兴 Vue 有一个内置的方法来处理这个
【解决方案2】:

你在传递 props 时犯了一个错误,如下所示:

<el-form v-bind="formProps" label-position=":labelPosition">
    <slot />
</el-form>

以上代码中label-position=":labelPosition"是错误的。

应该是:label-position="labelPosition",所以;

<el-form v-bind="formProps" :label-position="labelPosition">
    <slot />
</el-form>

【讨论】:

  • 感谢会修复,但如前所述,它是伪代码,而不是问题的根源
猜你喜欢
  • 2021-03-07
  • 2017-06-23
  • 2019-11-08
  • 2020-01-09
  • 2016-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
相关资源
最近更新 更多