小编Tho*_*ore的帖子

如何在defineProps中设置本地默认值?

我尝试使用 将 prop 的默认值设置为本地值i18n。我正在使用 Vue 3.2 和脚本设置标签。

我已尝试以下操作,但这给了我一个错误:

DefineProps 引用本地声明的变量。

<script setup>
import { useI18n } from 'vue-i18n';
    
const { t } = useI18n();
    
defineProps({
  type: { type: String, required: true },
  title: { type: String, required: false, default: `${t('oops', 1)} ${t('request_error', 1)}` },
  description: { type: String, required: false, default: '' },
  showReload: { type: Boolean, required: false, default: false },
  error: { type: String, required: true },
});
</script>
Run Code Online (Sandbox Code Playgroud)

处理这个问题的最佳方法是什么?

internationalization vuejs3

16
推荐指数
2
解决办法
3万
查看次数

可以使用正则表达式重写此函数吗?

我想重新格式化并验证用户是否提供了有效的比利时企业编号。由于输入可以是以下所有示例:

  • 是0123.321.123
  • BE0123.321.123
  • BE0123 321 123
  • 0123.321.123
  • 123.321.123
  • 123321123

我编写了一个函数,用于验证输入并将其重新格式化为“显示”版本(BE 0123.123.123)和“代码”版本(123123123)。此功能如下所示。

formatAndValidateEnterpriseNumber = enterpriseNumber => {
    if(enterpriseNumber === undefined || !enterpriseNumber || (enterpriseNumber || '').length < 3) return { isValid: false, error: 'Please fill in your enterprise number' };

        //Remove space, dots, ...
        enterpriseNumber = enterpriseNumber.toUpperCase();
        enterpriseNumber = enterpriseNumber.replace(/[. ,:-]+/g, '');

        //Check for double country code
        const reDouble = /^[a-zA-Z]{4}/;
        if (reDouble.test(enterpriseNumber)) enterpriseNumber = enterpriseNumber.substring(2);

        if (enterpriseNumber.length < 9 || enterpriseNumber.length > 12) return { isValid: false, error: 'The length …
Run Code Online (Sandbox Code Playgroud)

javascript regex reformatting

10
推荐指数
1
解决办法
287
查看次数

使用动态嵌套属性键对数组中的对象进行排序

我正在尝试对嵌套对象数组进行排序.它使用静态选择键,但我无法弄清楚如何动态获取它.

到目前为止,我已经有了这段代码

sortBy = (isReverse=false) => {
    this.setState(prevState => ({
        files: prevState.files.sort((a, b) => {
            const valueA = (((a || {})['general'] || {})['fileID']) || '';
            const valueB = (((b || {})['general'] || {})['fileID']) || '';

            if(isReverse) return valueB.localeCompare(valueA);

            return valueA.localeCompare(valueB);
        })
    }));
}
Run Code Online (Sandbox Code Playgroud)

此时键是硬编码的,['general']['orderID']但我想通过向函数添加一个keys参数来使这部分变为动态sortBy:

sortBy = (keys, isReverse=false) => { ...
Run Code Online (Sandbox Code Playgroud)

keys是一个嵌套键的数组.对于上面的例子,它将是['general', 'fileID'].

为实现这一目标需要采取哪些步骤?

注意:子对象可能是未定义的,因此我正在使用 a || {}

注2:我正在使用es6.没有外部包.

javascript arrays sorting object ecmascript-6

9
推荐指数
1
解决办法
429
查看次数

Vue 3:等待父级完成数据获取以获取子级数据并显示加载器

我正在寻找一种可重用的方式来显示完整页面加载器(侧边栏始终可见,但加载器应覆盖页面的内容部分),直到完成所有必要的 api 获取。

我有一个LaunchDetails包含在PageLoader组件中的父组件

LaunchDetails.vue

<template>
  <PageLoader>
    <router-link :to="{ name: 'launches' }"> Back to launches </router-link>
    <h1>{{ name }}</h1>

    <section>
      <TabMenu :links="menuLinks" />
    </section>

    <section>
      <router-view />
    </section>
  </PageLoader>
</template>

<script>
import TabMenu from "@/components/general/TabMenu";

export default {
  data() {
    return {
      menuLinks: [
        { to: { name: "launchOverview" }, display_name: "Overview" },
        { to: { name: "launchRocket" }, display_name: "Rocket" },
      ],
    };
  },
  components: {
    TabMenu,
  },
  created() {
    this.$store.dispatch("launches/fetchLaunch", this.$route.params.launch_id);
  },
  computed: { …
Run Code Online (Sandbox Code Playgroud)

vue.js axios vuex vuejs3

8
推荐指数
1
解决办法
4239
查看次数

React ref.current为null

我正在使用具有可变时间范围的议程/日历应用程序。要显示当前时间的一行并显示已进行的约会块,我需要计算给定时间范围内一分钟对应多少像素。

因此,例如:如果议程在上午7点开始,在下午5点结束,则总时间为10小时。假设日历的正文高度为1000像素。这意味着每小时代表100像素,每分钟代表1.66像素。

如果当前时间是下午3点。我们距议程开始只有480分钟的路程。这意味着显示当前时间的行应该在距日历正文顶部79.68像素(480 * 1.66)的位置。

计算没有问题,但获得议程主体的高度。我当时在考虑使用React Ref来获取高度,但出现错误:ref.current is null

下面的一些代码:

class Calendar extends Component {
    calendarBodyRef = React.createRef();

    displayCurrentTimeLine = () => {
        const bodyHeight = this.calendarBodyRef.current.clientHeight; // current is null
    }

    render() {
        return (
            <table>
                <thead>{this.displayHeader()}</thead>
                <tbody ref={this.calendarBodyRef}>
                    {this.displayBody()}
                    {this.displayCurrentTimeLine()}
                </tbody>
            </table>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

ref reactjs

7
推荐指数
2
解决办法
5287
查看次数

React路由器嵌套路由 - 如何在没有路由匹配时重定向

我正在构建一个包含三个主要部分的Web应用程序:实际网站,管理部分和用户部分.对于每个部分,我想要一个不同的布局包装器.

这是我现在的代码:

网站包装

const Website = () => (
  <React.Fragment>
    <NavigationBar />
    <main>
      <div className="container">
        <Switch>
          <Route exact path='/' component={Home}/>
          <Route exact path='/login' component={Login}/>
        </Switch>
      </div>
    </main>
    <FooterBar />
  </React.Fragment>
);
Run Code Online (Sandbox Code Playgroud)

用户包装器

const User = () => (
  <React.Fragment>
    <UserSideBar />
    <main>
      <div className="container">
        <Switch>
          <Route exact path='/u/dashboard' component={UDashboard}/>
          <Route exact path='/u/account' component={UAccount}/>
        </Switch>
      </div>
    </main>
  </React.Fragment>
);
Run Code Online (Sandbox Code Playgroud)

管理包装器

const Admin = () => (
  <React.Fragment>
    <main>
    <div className="container">
      <Switch>
        <Route exact path='/a/dashboard' component={ADashboard}/>
        <Route exact path='/a/payments' component={APayments}/>
        <Route exact …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-router

6
推荐指数
1
解决办法
977
查看次数

ReactJS中的多语言网站

我正在寻找一种以多种语言翻译完整网站(主页,关于我们,产品页面,联系方式,常见问题等等)的方法。该网站是在带有Firebase数据库的ReactJS中构建的。

我发现的所有示例都是小翻译,例如问候语,或者您如何?但是完整的网站又如何呢?我最好的选择是为每种语言制作一个JS对象,并使用数百个(可能是数千个)模板字符串吗?(那肯定会以“ homepageContactSectionSubDiscription”或“ homepageProductSectionFeaturesItemTwo”之类的标签结尾)

javascript multilingual reactjs

5
推荐指数
1
解决办法
3620
查看次数

如何使用 Apollo 和 NextJS 将数据转发到下一页

我正在使用 NextJS、Apollo 和 React(钩子)开发一个网络应用程序。

我有一个表格,它在注册过程的第一步中询问访问者的姓名。提交表单时,名称将保存在 Apollo 缓存中,访问者将被重定向到下一页。

import React, { useState } from 'react';
import Router , {useRouter}  from 'next/router';
import { useApolloClient } from '@apollo/react-hooks';


const NameForm = props => {
    const [name, setName] = useState("");
    const client = useApolloClient();
    const router = useRouter();

    const handleSubmit = e => {
        e.preventDefault();

        if(!name) return;

        client.writeData({ data: { name } });
        router.push('/user/register');
    }

    return (
        <form onSubmit={handleSubmit}>
            <div>
                <label htmlFor="name">Naam</label>
                <div>
                    <input type="text" id="name" name="name" value={name} onChange={e => setName(e.target.value)} />
                    <button …
Run Code Online (Sandbox Code Playgroud)

apollo next.js apollo-client react-hooks

5
推荐指数
0
解决办法
699
查看次数

Vue 在表单内按 Enter 键时防止表单提交

我有一个具有多个表单的网络应用程序,并且在这些表单内有多个自定义组件:输入、文本区域、选择框、日期选择器、单选按钮、复选框,...。

我发现当在表单标签的子组件内按 Enter 键时会触发提交函数。我不想要的东西。我希望能够使用回车键执行其他操作,例如确认下拉列表中的选择。

表格示例

<template>
    <form @submit.prevent="handleLogin">
        <fieldset :disabled="isSubmitting" class="space-y-6">
            <Input :label="$tc('email', 1)" type="email" id="email" v-model="user.email" :error="errors.email" />
            <Input :label="$tc('password', 1)" type="password" id="password" v-model="user.password" :error="errors.password" />
            <Select :label="$tc('role', 1)" id="role" :options="roles" displayProperty="display_name" valueProperty="id" v-model="user.role" :error="errors.role" />
            <SubmitButton :label="$tc('register', 1)" :submittingLabel="$tc('register_loader', 1)" :isSubmitting="isSubmitting" />
        </fieldset>
    </form>
</template>
Run Code Online (Sandbox Code Playgroud)

提交按钮.vue

<button type="submit">{{ isSubmitting ? submittingLabel : label }}</button>
Run Code Online (Sandbox Code Playgroud)

因此,我正在寻找一种方法来防止默认行为。添加 keydown 函数并检查是否在所有自定义组件中按下了 Enter 键,然后添加了 ,但event.preventDefault()没有成功。

一个可行的解决方案应该是将按钮的类型从“提交”更改为“按钮”并使用@click,但这听起来不像语义html。

还有其他建议吗?

javascript forms vue.js

5
推荐指数
1
解决办法
4496
查看次数

Vue3:检查事件监听器是否绑定到组件实例

我有一个可重复使用的徽章组件。我希望能够在组件实例上存在 onDelete 事件侦听器时添加关闭/删除按钮。

<template>
    <div class="flex inline-flex items-center px-2.5 py-0.5 text-xs font-medium select-none" :class="[square ? '' : 'rounded-full']">
        <slot />
        <button class="cursor-pointer ml-2" @click="$emit('onDelete')">
            <XIcon class="flex-shrink-0 h-3.5 w-3.5 text-gray-400 hover:text-gray-500" aria-hidden="true" />
        </button>
    </div>
</template>

<script>
    import { XIcon } from '@heroicons/vue/solid';

    export default {
        props: {
            color: { type: String },
            square: { type: Boolean, default: false },
        },
        components: {
            XIcon,
        },
        emits: ['onDelete'],
    };
</script>
Run Code Online (Sandbox Code Playgroud)

如果我向按钮添加 v-if 语句,则立即执行发出事件

<button v-if="$emit('onDelete')" class="cursor-pointer ml-2" @click="$emit('onDelete')">
Run Code Online (Sandbox Code Playgroud)

我正在使用Vue 3

vue.js vuejs3

5
推荐指数
1
解决办法
7314
查看次数