AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

问题[vuejs3](coding)

Martin Hope
shan zi
Asked: 2025-04-25 10:27:24 +0800 CST

Tailwind@4 无法在 Storybook@8 中使用

  • 6

我创建了一个新的 vue3 + Vite,Storybook 项目。

"@storybook/vue3": "^8.6.12",
"@storybook/vue3-vite": "^8.6.12",
"vite": "^6.2.0",

并安装这些 npm 包:

"@storybook/addon-postcss": "^2.0.0",
"@tailwindcss/postcss": "^4.1.4",
"postcss": "^8.5.3",
"tailwindcss": "^4.1.4",
// and edit .storybook/main.ts
addons: [
+    {
+      name: "@storybook/addon-postcss",
+      options: {
+        postcssLoaderOptions: {
+          implementation: require("postcss"),
+        },
+      },
+    }
]
// and edit .storybook/preview.ts
+ import '../packages/style/tailwindcss.css'
/* content of the packages/style/tailwindcss.css  */
@import "tailwindcss";
// add the postcss.config.js
module.exports = {
    plugins: {
        '@tailwindcss/postcss': {},
        // autoprefixer: {}
        // require('postcss-color-rebeccapurple'),
    }
}
// edit package.json
  - "type": "module"
  
Why delete this line?

Failed to load PostCSS config (searchPath: /Users/lifaqi/noliebe/tool-cabinet): [ReferenceError] module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/Users/lifaqi/noliebe/tool-cabinet/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
ReferenceError: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/Users/lifaqi/noliebe/tool-cabinet/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///Users/lifaqi/noliebe/tool-cabinet/postcss.config.js?t=1745546527838:1:1
    at ModuleJob.run (node:internal/modules/esm/module_job:271:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:578:26)
    at async req$3 (file:///Users/lifaqi/noliebe/tool-cabinet/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-glQox-ep.js:14751:13)
    at async Object.search (file:///Users/lifaqi/noliebe/tool-cabinet/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-glQox-ep.js:14493:23)

so i delete them, run stoybook, and is clear.

但是 tailwindcss 无法在我的组件上运行。我该怎么办?这是我第一次使用 Storybook。我使用[email protected]

vuejs3
  • 1 个回答
  • 31 Views
Martin Hope
Andrei Maieras
Asked: 2025-04-10 18:30:54 +0800 CST

Vuetify v-select 带有搜索输入更改选定的值

  • 6

我正在使用 Vuetify 3+,并尝试添加一个文本输入框,以便搜索传递给 V-Select 组件的元素。问题是,当我执行搜索并在内部更改 items 属性输入时,V-Select 组件会更改 V-Model,从而选择搜索到的元素(如果有)。我不希望出现这种情况,我希望只有当我明确点击该元素的复选框时才会进行选择。

<v-select
      :item-title="itemTitle"
      :item-value="itemValue"
      :items="filteredItems"
      :loading="!disabled ? loading : false"
      :menu-props="menuProps"
      :model-value="modelValue"
      :name="name"
      :placeholder="placeholder"
      :prepend-inner-icon="icon"
      :readonly="disabled"
      :required="required"
      :return-object="returnObject"
      :rules="rules"
      attach
      width="220px"
      class="custom-menu-select"
      dense
      density="compact"
      hide-details
      @update:model-value="updateModelValue"
      @update:menu="updateMenu"
    >
      <template v-if="enableSearch" #prepend-item>
        <div class="sticky-header">
          <v-text-field
            v-model="searchQuery"
            :loading="loadingSearch"
            :placeholder="searchLabel"
            append-inner-icon="ibm:Search16"
            class="select-search-input"
            clearable
            density="compact"
            hide-details
            variant="outlined"
            @click:clear="searchQuery = ''"
          ></v-text-field>
        </div>
      </template>
      <template #selection="{ item }">
        <slot :item="item" name="selection">
          <span>{{ item ? item['title'] : placeholder }}</span>
        </slot>
      </template>
      <template #item="{ props, item }">
        <slot :item="item" :props="props" name="item">
          <TooltipPopup
            :disabled="!item.raw.disabled || !item.raw.tooltip"
            :tooltip="item.raw.tooltip"
            placement="right"
          >
            <template #activator>
              <v-list-item
                :disabled="item.raw.disabled"
                density="compact"
                v-bind="props"
              ></v-list-item>
            </template>
          </TooltipPopup>
        </slot>
      </template>
    </v-select>

上面是我的选择组件,这里是我的过滤计算(我尝试使用克隆和不使用克隆,仍然得到相同的结果)

const filteredItems = computed(() => {
  const clonedItems = [...props.items]
  if (!props.enableSearch) return clonedItems
  if (props.serverSearch) return localItems.value
  if (!searchQuery.value) return clonedItems
  return clonedItems.filter((item) =>
    item[props.itemTitle].toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

带有复制问题的游乐场链接

vuejs3
  • 1 个回答
  • 22 Views
Martin Hope
user824624
Asked: 2025-02-11 20:27:50 +0800 CST

如何覆盖元素的 CSS 变量的值?

  • 5

目前正在使用 primevue,但按钮看起来太大了,y 填充如图所示

左按钮是 primevue 按钮,右按钮是我想要的。

左按钮是 primevue 按钮,右按钮是我想要的。

查看按钮 css,我发现它与填充有关:var(--p-button-padding-y);

.p-button {
    display: inline-flex;
    cursor: pointer;
    user-select: none;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    position: relative;
    color: var(--p-button-primary-color);
    background: var(--p-button-primary-background);
    border: 1px solid var(--p-button-primary-border-color);
    padding: var(--p-button-padding-y) var(--p-button-padding-x);
}

那么我该如何在我的 vue3 项目中编辑变量 - (--p-button-padding-y)?

vuejs3
  • 1 个回答
  • 33 Views
Martin Hope
moxi
Asked: 2025-02-10 21:22:17 +0800 CST

消息已添加但未显示

  • 5

PrimeVue ToastEventBus 中的 toastmessages 已添加到 DOM 中,但未显示。有人知道为什么吗?

根据这个答案,我在页面中有以下内容。

<!doctype html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <script type="text/javascript" src="https://unpkg.com/vue@3/dist/vue.global.prod.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script type="text/javascript" src="https://unpkg.com/primevue/umd/primevue.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script type="text/javascript" src="https://unpkg.com/@primevue/themes/umd/aura.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  </head>
  <body>
    <div id="test-toastbutton"></div>
    <script type="module">
      import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'

      const app = createApp({
        setup() {
          const addToast = () => {
            PrimeVue.ToastEventBus.emit('add', { severity: 'info', summary: 'Info', detail: 'Message Content', life: 3000 })
          }

          return { addToast };
        },
        template: '<Toast /><button @click="addToast">Adding toast</button>'
      })
      app.use(PrimeVue.Config, {
        theme: {
            preset: PrimeVue.Themes.Aura
        }
      })
      app.component('Toast', PrimeVue.Toast)
      app.mount('#test-toastbutton')
    </script>
  </body>
</html>

在控制台中我看到警告:

[Vue warn]: Missing ref owner context. ref cannot be used on hoisted vnodes. A vnode with ref must be created inside the render function. 
  at <Toast> 
  at <App>

我期望 toast 能够显示出来。但我只看到它们被添加到了 DOM 中:

<body>
  <div id="test-toastbutton" data-v-app="">
    <portal>
      <div class="p-toast p-component p-toast-top-right" data-pc-name="toast" pc1="" data-pc-section="root" style="position: fixed; top: 20px; right: 20px;">
        <div>
          <toastmessage message="[object Object]" templates="[object Object]"></toastmessage>
          <toastmessage message="[object Object]" templates="[object Object]"></toastmessage>
          <toastmessage message="[object Object]" templates="[object Object]"></toastmessage>
          ...

vuejs3
  • 1 个回答
  • 19 Views
Martin Hope
1K412
Asked: 2025-02-06 20:33:06 +0800 CST

Vuetify 服务器数据表分页无法正常工作

  • 6

我正在尝试实现一个从 API 请求(响应返回数据和元数据)填充的服务器数据表。

但是,用于转到下一页的分页按钮无法正常工作。当数据加载时,它们会立即启用,然后禁用。后端返回正确的数据,当我快速单击下一页按钮时,会触发 OnPageChange() 并打印下一页 (2)。

我声明 v-data-table 如下:

<v-data-table 
        v-model:items-per-page="itemsPerPage" 
        :headers="headers" 
        :items="users"
        :server-items-length="totalItems" 
        :loading="loading" 
        item-key="id"           
        @update:options="fetchUsers({ page: page, itemsPerPage: itemsPerPage, search: search })"   
        :items-per-page-options="itemsPerPageOptions" 
        :page="page" @update:page="onPageChange">

该脚本具有:

data() {
        return {
            users: [],
            totalItems: 1,
            itemsPerPage: 5,
            page: 1,
            loading: false,
            search: '',
            itemsPerPageOptions: [5, 10, 50],
            ...
methods: {
        async fetchUsers({ page, itemsPerPage, search = this.search }) {
            this.loading = true;

            try {
                const response = await axios.get(`/users`, {
                    params: {
                        page,
                        per_page: itemsPerPage,
                        search: this.search.trim() || '',
                    },
                });

                this.users = response.data.data;
                this.totalItems = response.data.meta.total;

            } catch (error) {
                console.error('Error fetching users:', error);
            } finally {
                this.loading = false;
            }
        },
        onPageChange(newPage) {
            this.page = newPage;
            console.log(newPage);
            this.fetchUsers({
                page: this.page,
                itemsPerPage: this.itemsPerPage,
                search: this.search
            });
        },

vuetify 分页是否存在错误或者我遗漏了什么?

vuejs3
  • 1 个回答
  • 29 Views
Martin Hope
shazim ali
Asked: 2025-01-22 02:57:19 +0800 CST

Vuetify 3 | 如何使用可组合功能以编程方式关闭 dailog

  • 4

你好,我在 vuetify 3 中进行 crud 操作,为了创建表单,我正在使用 v-dailog,我想在表单成功将数据保存到服务器后关闭 v-dailog。我已经使用 composable 来处理我的所有逻辑。让我分享我的代码。

我的组件文件

角色操作.vue

<template>
    <v-dialog max-width="800">
      <template v-slot:activator="{ props: activatorProps }">
        <v-btn
          v-bind="activatorProps"
          :text="btnTitle"
          @click="getAllPermissions(roleId)"
        ></v-btn>
      </template>

      <template v-slot:default="{ isActive }">
        <v-card :title="modalTitle">
          <template v-slot:text>
            <div v-if="loading" class=" d-flex justify-center">
              <v-progress-circular indeterminate></v-progress-circular>
            </div>
            <v-form v-else @submit.prevent="handleSubmit(roleId)">
              <v-row>
                <v-col cols="12">
                  <v-text-field
                  v-model="form.name"
                  :error-messages="errorMessages.name"
                  autofocus
                  label="Role Name"
                  type="text"
                  placeholder="Administrator Role"
                />
                </v-col>
                <v-col cols="12">
                  <div class="d-flex justify-space-between">
                    <h5>Role Permissions</h5>
                    <v-checkbox v-model="isSelectAllPermissions" @update:model-value="selectAllPermissions" label="Select All"></v-checkbox>
                  </div>
                  <v-container>
                    <v-row no-gutters>
                      <v-col v-for="permission in lstPermissions" :key="permission.id" cols="3">
                        <v-checkbox :value="permission.id" :label="permission.name" v-model="form.permissions"></v-checkbox>
                      </v-col>
                    </v-row>
                    <v-row no-gutters>
                      <v-col class="text-sm text-error">
                      {{ errorMessages.permissions }}
                      </v-col>
                    </v-row>
                  </v-container>
                </v-col>
              </v-row>
              <v-row>
                <v-col cols="12">
                  <v-btn
                  :text="roleId == 0 ? 'save':'update'"
                  variant="elevated"
                  type="submit"
                  class="mr-2"
                  :loading="formLoading"
                >
                <template v-slot:loader><v-progress-circular indeterminate></v-progress-circular> Save</template>
                </v-btn>
                <v-btn
                  text="Cancel"
                  variant="tonal"
                  @click="isActive.value = false"
                ></v-btn>
                </v-col>
              </v-row>
            </v-form>
          </template>
        </v-card>
      </template>
    </v-dialog>
</template>
<script setup lang="ts">

import { useRoleOperations } from '@/composable/useRoleOperations';
  const props = defineProps<{
          btnTitle: string,
          modalTitle:string,
          roleId:number
       }>()
  const { 
    lstPermissions,
    loading,
    getAllPermissions,
    form,
    errorMessages,
    handleSubmit,
    formLoading,
    selectAllPermissions,
    isSelectAllPermissions
    } = useRoleOperations();
</script>

我的可组合文件

useRoleOperations.ts

import { IPermissionsList, IRole } from "@/Interfaces/IRole";
import { fetchAllPermissions, fetchRoleByID, saveRole, updateRole } from "@/services/RolesService";
import { toast } from 'vue3-toastify';

export function useRoleOperations (){
    
    const lstPermissions = ref<IPermissionsList>([]);
    const loading = ref<boolean>(false);
    const formLoading = ref<boolean>(false);
    const isSelectAllPermissions = ref<boolean>(false);
    const form = ref<IRole>({
        name:'',
        permissions:[]
    });

    const selectAllPermissions = () => {
        if(isSelectAllPermissions.value == true){
            isSelectAllPermissions.value = true;
            form.value.permissions = lstPermissions.value.map(({id}) => id);
        }
        if(isSelectAllPermissions.value == false){
            form.value.permissions = []
            isSelectAllPermissions.value = false;
        }
        
    }
    const errorMessages = ref<[name:string, permissions: string]>([]);

    const getAllPermissions = (id:number) => {
        form.value.name= '';
        form.value.permissions=[];
        loading.value = true;

        //get all permissions
        fetchAllPermissions().then((res) => {
            
            lstPermissions.value = res.data.data
            
            //get selected permissions in role edit case
            if(id != 0){
                fetchRoleByID(id).then((res) => {
                    let data = res.data.data;
                    form.value.name = data.name;
                    form.value.permissions = data.permissions.map(({id}) => id);

                    if(form.value.permissions.length  == lstPermissions.value.length){
                        isSelectAllPermissions.value = true;
                    }
                }).catch((err) => {
                    toast.error(err.message)
                    loading.value = false;
                 })
            }

            loading.value = false;
            }).catch((err) => {
            toast.error(err.message)
            loading.value = false;
         })
        
    }

    const handleSubmit = (id:number) => {
        formLoading.value = true;
        if(id == 0){
            saveRole(form.value).then((res) => {
                formLoading.value = false;
            toast.success(res.data.message)
            })
            .catch((err) => {
              if(err.response.status == "422"){
                errorMessages.value =  err.response.data.errors
                formLoading.value = false;
              }else if(err.response.status == "401"){  
                toast.error(err.response.data.message);
                formLoading.value = false;
                errorMessages.value = ['','']
              }else{
                toast.error(err.message)
                formLoading.value = false;
              }
            })
        }else{
            updateRole(id,form.value).then((res) => {
                formLoading.value = false;
            toast.success(res.data.message)
            })
            .catch((err) => {
              if(err.response.status == "422"){
                errorMessages.value =  err.response.data.errors
                formLoading.value = false;
              }else if(err.response.status == "401"){  
                toast.error(err.response.data.message);
                formLoading.value = false;
                errorMessages.value = ['','']
              }else{
                toast.error(err.message)
                formLoading.value = false;
              }
            })
        }

        // here i wanted to close V-DAILOG programatically
    }
    return {
        lstPermissions,
        loading,
        getAllPermissions,
        selectAllPermissions,
        handleSubmit,
        errorMessages,
        isSelectAllPermissions,
        formLoading,
        form
    }
}

期待帮助。

vuejs3
  • 1 个回答
  • 23 Views
Martin Hope
joseph son
Asked: 2025-01-13 20:19:45 +0800 CST

为什么将一个应用程序加载到两个 div 不起作用

  • 5

你们能告诉我我这里遗漏了什么吗?我试图加载一app到两个,div但我发现它只适用于第一个。

下面,我期待的消息div2app1没有到来。提前致谢

<div id="div1app1">
    This is div1 for app1 {{ message }} 
</div>  

<!--lots of html an JS in between -->

<div id="div1app2">
  This is div1 for app2 {{ msg }}   
</div> 

<!--lots of html an JS in between -->   
   
<div id="div2app1">
   This is div2 for app1 {{ message }}   
</div> 


<script type="module">
import { createApp, ref, defineProps, onMounted, shallowReactive, reactive } from 'vue'
      
const app1 = createApp({
  setup() {
    onMounted(async () => {
      console.log('Hello')     
      message.value = 'New Hello'
    })  
    const message = ref('Hello Vue!')
    return {              
      message
    }
  }
})
const app2 = createApp({
  setup() {
    onMounted(async () => {
      console.log('Hello')
      msg.value = 'Hello for App2'
    })

    const msg = ref('Hello Vue!')
    return {       
      msg
    }
  }
})  

app1.mount('#div1app1');
app1.mount('#div2app1');
app2.mount('#div1app2');

</script>
vuejs3
  • 1 个回答
  • 50 Views
Martin Hope
Mathew Paret
Asked: 2025-01-13 04:40:37 +0800 CST

导入包时,npm 包中的 vue 组件使用的 Tailwind 类不可用

  • 5

我有以下 Vue 组件:

// src/components/CodeBlock.vue
<script setup>
    import { ref } from 'vue';

    const props = defineProps({
        value: String
    })

    const text = ref(null)
    const copied = ref(false)

    const copyText = (data) => {
        navigator.clipboard.writeText(data);
        copied.value = true;
        setTimeout(() => copied.value = false, 1000)
    }
</script>
<template>

<div class="w-full">
    <div class="relative">
        <label for="npm-install-copy-button" class="sr-only">Label</label>
        <code ref="text" class="col-span-6 bg-gray-50 border border-gray-300 text-gray-500 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-400 dark:focus:ring-blue-500 dark:focus:border-blue-500" disabled readonly>
            <slot>{{ props.value }}</slot>
        </code>
        <button type="button" @click.prevent="copyText(text.innerText)" data-tooltip-target="tooltip-copy-npm-install-copy-button" class="absolute end-2 bottom-1 translate-y-1 text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg p-1 mb-1 inline-flex items-center justify-center hover:text-gray-900 dark:hover:text-white">
            <span id="default-icon" v-if="!copied">
                <svg class="w-3.5 h-3.5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 18 20">
                    <path d="M16 1h-3.278A1.992 1.992 0 0 0 11 0H7a1.993 1.993 0 0 0-1.722 1H2a2 2 0 0 0-2 2v15a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2Zm-3 14H5a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2Zm0-4H5a1 1 0 0 1 0-2h8a1 1 0 1 1 0 2Zm0-5H5a1 1 0 0 1 0-2h2V2h4v2h2a1 1 0 1 1 0 2Z"/>
                </svg>
            </span>
            <span id="success-icon" class="inline-flex items-center" v-if="copied">
                <svg class="w-3.5 h-3.5 text-blue-700 dark:text-blue-500" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 12">
                    <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M1 5.917 5.724 10.5 15 1.5"/>
                </svg>
            </span>
        </button>
        <div id="tooltip-copy-npm-install-copy-button" role="tooltip" class="absolute z-10 invisible inline-block px-3 py-2 text-sm font-medium text-white transition-opacity duration-300 bg-gray-900 rounded-lg shadow-sm opacity-0 tooltip dark:bg-gray-700">
            <span id="default-tooltip-message">Copy to clipboard</span>
            <span id="success-tooltip-message" class="hidden">Copied!</span>
            <div class="tooltip-arrow" data-popper-arrow></div>
        </div>
    </div>
</div>
</template>

我的 npm 包package.json看起来像这样:

{
    "name": "@pioneer-dynamics/code-block",
    "description": "A simple way to disaply a block of code that has a click to copy option.",
    "version": "1.0.0",
    "author": "Mathew Paret <[email protected]>",
    "license": "MIT",
    "main": "src/components/CodeBlock.vue",
    "dependencies": {
      "vue": "^3.0.0"
    },
    "browserslist": [
      "> 1%",
      "last 2 versions",
      "not ie <= 8"
    ]
  }

当我在没有 npm 模块的情况下使用此组件时(即将 .vue 文件复制到我的使用项目的文件夹 [不在 node_modules 内],UI 将按预期呈现)。

import CodeBlock from '@/Components/CodeBlock.vue';

直接使用时,不要从 npm 包中获取

当我使用 NPM 模块中的组件时,UI 看起来很糟糕。

import CodeBlock from '@pioneer-dynamics/code-block

从 npm 包中使用时

我该如何修复 UI!?

创建了一个将在多个项目中使用的 vue 组件,将其移动到 NPM 包并尝试将其导入使用项目中。

预期 UI 和功能将以相同的方式运行。

UI 似乎没有按预期工作,但功能却按预期工作。

vuejs3
  • 1 个回答
  • 11 Views
Martin Hope
Tyssen
Asked: 2024-12-18 12:22:21 +0800 CST

Vue3 组件中不可用的 Props

  • 5

我在 Twig 模板中有这个:

<div
    class="multiSelect"
    id="{{ id }}"
    data-options="{{ options|json_encode }}"
    data-field="{{ handle }}"
>
    <div class="selectComponent"></div>
</div>

以及执行挂载的 js 文件:

multiSelects.forEach((el) => {
   const component = el.querySelector('.selectComponent');
   const options = el.dataset.options || '[]';
   const field = el.dataset.field || '';
   console.log('Field before mounting:', field);
   console.log('Items before mounting:', options);
   const multiSelect = createApp(MultiSelect);
   multiSelect.use(vuetify).mount(component, {
       props: {
           items: options,
           field: field,
       }
    });
});

它将正确的值输出到控制台。

页面上确实呈现了组件,但显示“无可用数据”。控制台中输出的是空字符串或数组。

这是该组件的代码。

<template>
  <v-select
    v-model="selectedvalue"
    :items="items"
    :name="field"
    item-text="title"
    item-value="id"
    label=""
    chips
    multiple
  ></v-select>
</template>

<script>
  export default {
    props: {
      items: {
        type: Array,
        default: () => []
      },
      field: {
        type: String,
        default: ''
      }
    },
    data() {
      console.log('After mounting items:', this.items);
      console.log('After mounting field:', this.field);
      return {
        selectedvalue: [],
      }
    }
  }
</script>

所以看起来组件中的 props 没有被正确拾取。这是为什么呢?

vuejs3
  • 1 个回答
  • 14 Views
Martin Hope
Eugene Karataev
Asked: 2024-12-16 12:54:27 +0800 CST

如何禁用 HTML 输入中的第一个空格?

  • 7

考虑一个带有文本输入的简单 Vue 组件(链接)。

<script setup>
import { ref } from 'vue'

const msg = ref('')

function onInput(e) {
  let value = e.target.value;
  if (value === ' ') value = '';
  msg.value = value;
}
</script>

<template>
  <input :value="msg" @input="onInput" />
</template>

我想禁用此输入中的第一个空格,即如果用户输入空格,则输入字段应保持为空。但不起作用。我猜这是因为 Vue 检查了msg没有变化并拒绝了组件渲染。

我的下一次尝试是强制渲染组件(链接)。

<script setup>
import {getCurrentInstance} from 'vue'
import { ref } from 'vue'

const msg = ref('')

const instance = getCurrentInstance();

function onInput(e) {
  let value = e.target.value;
  if (value === ' ') {
    value = '';
    msg.value = value;    
    instance?.proxy?.$forceUpdate();
    return;
  }
  msg.value = value;
}
</script>

<template>
  <input :value="msg" @input="onInput" />
</template>

它可以工作,但有限制。我的项目有一个很大的组件树,并且$forceUpdate只更新当前组件,没有子组件。

key我也尝试通过改变组件来重新渲染整个子三,但在这种情况下我失去了输入的焦点。

总而言之,我似乎错过了一些东西。我不敢相信如此简单的任务需要奇怪的解决方法。请帮我找到一种简单且“最佳实践”的方法来禁用 html 输入中的第一个空格。

PS React 版本按预期工作。

import React, {useState} from 'react';

export function App(props) {
  const [value, setValue] = useState('');

  function onInput(e) {
    let v = e.target.value;
    if (v === ' ') v = '';
    setValue(v);
  }

  return (
    <div className='App'>
      <input value={value} onInput={onInput} />
    </div>
  );
}
vuejs3
  • 3 个回答
  • 73 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve