标签: vue-props

Vue 子组件不会在 Prop 更改时更新

我正在更新一个“锻炼”道具,该道具被发送到 Vue 中的“锻炼”组件。在子组件中,我发出一个函数来增加您所在的集合。该函数在父组件中触发(我得到的是 console.logs()),但子组件没有重新渲染。

家长:

<ExerciseListItem
  v-for="(exercise) in exercises"
  v-on:completeSet="completeSet"
  v-on:selectExercise="selectExercise"
  v-bind:exercise.sync="exercise"
  v-bind:isActiveExercise="exercise.slug === activeExerciseSlug"
  v-bind:key="exercise.slug"
/>
Run Code Online (Sandbox Code Playgroud)

方法:

methods: {
  completeSet: function(slug) {
    console.log("complete-set", slug);
    const exercise = this.getExerciseBySlug(slug);
    exercise.completedSets++;
    if (exercise.completedSets === exercise.totalSets) {
      this.completeExercise(slug);
    }
  },
  completeExercise: function(slug) {
    this.getExerciseBySlug(slug).isComplete = true;
    console.log("COMPLETE-exercise", slug);
  },
  getExerciseBySlug: function(slug) {
    return this.exercises.find(exercise => exercise.slug === slug);
  },
  selectExercise: function(selectedSlug) {
    this.activeExerciseSlug = selectedSlug;
  }
},
Run Code Online (Sandbox Code Playgroud)

子模板

<li
  v-bind:class="{ 'white-box': true, complete: exercise.isComplete }"
  v-on:click="exercise.totalSets > 1 ? $emit('selectExercise', exercise.slug) : …
Run Code Online (Sandbox Code Playgroud)

javascript data-binding components vue.js vue-props

5
推荐指数
2
解决办法
6812
查看次数

如何使用 props 为 Vue 中的组件创建动态背景图片?

客观的

我想将图像的路径作为道具传递给组件。我希望组件使用 prop 来动态生成背景图像。

我的所有图像都位于 Vue src 文件夹中的 asset 文件夹中。该路径看起来像“@/assets/images/subject/computers.jpeg”

问题

没有背景图像出现

这是页面上呈现的内容:

在此输入图像描述

然而,什么也没有出现

奇怪的行为

由于某种原因,在 CSS 中添加完全相同的路径名“@/assets/images/subject/computers.jpeg”是可行的(将其添加到 <style> 标签中)。如果它是 v-bind 内联样式,它就不起作用。

这是我的 CSS 中的样子

在此输入图像描述

但问题是它不是动态渲染的 CSS。

我进一步检查了该元件并发现了一些奇怪的行为。如您所见,内联样式将图像路径读取为“@/assets/images/subject/computers.jpeg”(下图中的 element.style)。

在 CSS 中添加路径时,将'@/assets/images/subject/computers.jpeg'更改为'http://localhost:8080/img/computers.7f3748eb.jpeg',然后正确渲染背景图像。

在此输入图像描述

问题

我想我的问题是双重的:

  1. 如何使用 props 在 Vue 中动态渲染背景图像?或者有更好的方法来做到这一点吗?
  2. 为什么绑定内联样式不能解析路径(继续使用“@”),而直接在 <script> 标签中添加它可以解析路径?

解决方案

好的,非常感谢taoBernard Borg帮助我解决了这个问题。

我能够使用计算属性来解决这个问题,如下所示:

const imgSrc = computed(() => require(`@/assets/images/subject/${props.subject.image}`))
Run Code Online (Sandbox Code Playgroud)

由于 VueLoader(Vue 中的默认设置)解析路径的方式,我无法将“@”路径存储在 prop 本身中。相反,该 prop 只是图像/文件名(例如“computers.jpeg”),并且使用 require() 的计算属性处理解析图像的前置路径。

之后,我将计算属性添加到绑定的内联样式中,如下所示:

<div …
Run Code Online (Sandbox Code Playgroud)

css data-binding vue.js vue-props vue-composition-api

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

Vuejs - 如何将 prop 的默认值设置为预定义数据?

问题很简单。我想定义 adata如下;

data() {
  return {
    logoURL: "some-link/some-picture.png"
  }
}
Run Code Online (Sandbox Code Playgroud)

我想将其设置为道具的默认状态,如下所示:

props: {
  infoLogoURL: {
    type: String,
    default: this.logoURL,
  },
}
Run Code Online (Sandbox Code Playgroud)

显然它没有按照我想要的方式工作,并且出现以下错误:

Uncaught TypeError: Cannot read property 'logoURL' of undefined
Run Code Online (Sandbox Code Playgroud)

我该如何处理这个问题?这是我如何使用道具的示例:

<cardComp
  infoTitle = "Info Title" 
  infoText = "Info Text" 
  infoSubIcon = "Sub Icon Name" 
  infoSubIconColor = "css-color-class" 
  infoSubText = "Sub Text" 
  infoDescription = "Some Text Description" 
  infoIcon = "Icon Name" 
  infoIconColor = "icon-color-css"
  infoLogoURL = "some-link/some-picture.png"
/>
Run Code Online (Sandbox Code Playgroud)

这是另一个问题...我想infoIcon在没有infoLogoURL. 假设该特定 .png 文件的链接暂时不可用,因此在这种情况下,我想显示 .png 文件 …

vue.js vue-props

4
推荐指数
1
解决办法
2426
查看次数

在 vue3 脚本设置中的 props 上使用 Watchers

我将一个 prop 传递给一个组件,声明它所处的状态。我想观看 prop 并相应地设置 css。但这不起作用,有人可以告诉我我做错了什么吗?

<script setup>
  import { onMounted, reactive, ref, watch, watchEffect } from 'vue'

  const props = defineProps({
    title: String,
    date: String,
    state: String,
  })

  let cardStatus = ref('')

  watch(props.state, () => {
    if (props.state === 'finished'){
      cardStatus.value = 'border border-success'
    }
  })
</script>

<template>
  <div :class="'bg-main-light rounded-2xl w-full p-3 lg:px-5 ' + cardStatus"></div>
</template>
Run Code Online (Sandbox Code Playgroud)

javascript vue.js vue-props vuejs3 vue-composition-api

4
推荐指数
1
解决办法
3057
查看次数

当我在 vue 3 脚本设置中将数组作为 prop 传递时,如何在 DefineProps 中初始化/为数组提供默认值

我已经传递了一个数组作为道具项,我在接口 Props 中给了它一个类型,当我尝试给它一个默认值时,我得到一个错误第四行我TS2322: Type 'never[]' is not assignable to type '(props: Readonly<Props>) => string[]'. \xc2\xa0\xc2\xa0Type 'never[]' provides no match for the signature '(props: Readonly<Props>): string[]'. 不确定我在这里做错了什么,因为这似乎适用于其他变量

\n
<script setup lang="ts">\nimport {ref} from "vue";\n\ninterface Props {\n  items?: Array<string>\n}\n\nconst props = withDefaults(defineProps<Props>(), {\n  items: []\n});\nlet selectedItem = ref(props.items[0])\n
Run Code Online (Sandbox Code Playgroud)\n

vue.js vue-props vuejs3

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

Vue 3 - 组合 API - 如何获取道具原始值

我有一个接收一些道具并发出自定义事件的组件。我需要发出来将 props 的值作为参数传递。无论我做什么,我总是收到一个代理而不是原始值。这是我的实现的简化:

    //child-component
    <script setup lang="ts">
        import { ref, unref } from "vue";

        const props = defineProps<{
             category: { id: number, label: string};
        }>();

        const emit = defineEmits(["sendcategory"]);
        const category = ref(props.category);
        const cat = unref(category);

        function send() {
            emit("sendcategory", cat);
       
    }
    <template>
       <div  @click="send" >
            {{ category.value.label }}
       </div>
    </template>
Run Code Online (Sandbox Code Playgroud)

这是父组件的示例

    //parent-component
    <script setup lang="ts">

        import { ref } from "vue";
        import ChildComponent from "./ChildComponent.vue";

        const item = { id: 1, label: "testlabel" }

        function getcategory(category: {id: number, …
Run Code Online (Sandbox Code Playgroud)

vue.js vue-reactivity vue-props vue-composition-api

2
推荐指数
1
解决办法
4984
查看次数

如何使用基于 props 的计算

我尝试根据 props 值计算一个值,如下所示:

interface Props {
  task: Task;
}

const totalPrice = computed(() => {
  return task.paymentDetail.products
    .map(p => p.amount)
    .reduce((partialSum, acc) => partialSum + acc, 0);
})
Run Code Online (Sandbox Code Playgroud)

然后在我的模板中,我显示计算值,totalPrice如下所示:{{ totalPrice }}

我的计算从来不是计算,如果我在里面添加一个console.log,我永远不会输入它。

如何根据 props 计算值?

computed-properties vue-props vuejs3 vue-composition-api

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

使用 Nuxt.js 将事件传递给父组件

我有一个简单的标题组件,其中包含一个可点击的汉堡包,我想将汉堡包分成一个单独的组件,但是当我这样做时,点击事件不再起作用,我想我需要某种布尔属性,但找不到解释或者我正在寻找错误的东西。

这作为单个组件工作

/components/Header.vue

<template>
  <div class="--row header__wrapper" :class="{active: menuClose}">
    <button class="hamburger" :class="{active: menuClose}" @click="menuClose=!menuClose">
      <span></span>
      <span></span>
      <span></span>
    </button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      menuClose: false,
    };
  }
};
</script>


Run Code Online (Sandbox Code Playgroud)

下面的内容不起作用,因为当分成两个组件时会丢失点击事件,这就是我陷入困境的地方。

/components/Header.vue

<template>
<div class="--row header__wrapper" :class="{active: menuClose}">
        <Hamburger/>
</div>
</template>

<script>
import Hamburger from "~/components/Hamburger.vue";
  export default {
    components: {
      Hamburger
    }
  }
};
</script>

Run Code Online (Sandbox Code Playgroud)

/组件/汉堡.vue

<template>
  <button class="hamburger" :class="{active: menuClose}" @click="menuClose=!menuClose">
    <span></span>
    <span></span>
    <span></span>
  </button>
</template>

<script>
export default {
  data() {
    return { …
Run Code Online (Sandbox Code Playgroud)

click vue-component vuejs2 nuxt.js vue-props

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

有条件地将@submit.prevent 添加到 Vue.js 的表单中

我正在尝试有条件地阻止使用@submit.prevent. 我有一个看起来像这样的通用表单模型(最小化一点):

<v-form v-model="valid">
   <div>
      <div v-for="(field, i) in fieldConfig" :key="`model-form-`+i">
         <fe-label v-if="field.label">{{field.label}}</fe-label>
         <component 
            :is="field.component" 
            v-bind="field.attrs" 
            v-model="item[field.field]"
          />
       </div>
   </div>
</v-form>
Run Code Online (Sandbox Code Playgroud)

从父母那里调用:

<model-form
   idProperty="id"
   @done="finishRename"
   model="myModel"
   :fieldConfig="fieldConfig"
   :htmlSubmit="false"
/>
Run Code Online (Sandbox Code Playgroud)

我在搜索中看到了一些类似的东西,但没有什么是正确的,而且我对 Vue 很陌生。任何帮助表示赞赏。谢谢!

vue.js vuetify.js vue-events vue-props

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

为什么道具的 Vue3 观察者不会被触发?(组合 API)

我拼命尝试watchpropVue3(3.2.31,Composition API)中:

\n
<script lang="ts" setup>\nimport { toRef, watch } from \'vue\'\n\nconst props = defineProps({\n  \'trigger-refresh\': {\n    type: String\n  }\n})\nconst triggerRefresh = toRef(props, \'trigger-refresh\')\nwatch(triggerRefresh, (a, b) => console.log(\'props triggered refresh\'))\n</script>\n
Run Code Online (Sandbox Code Playgroud)\n

我触发了 的发射trigger-refresh,它通过上面的代码传递给组件,并且我看到triggerRefreshDevTools\xe2\x86\x92Vue 中发生了变化

\n

watch因此,除了未触发(即控制台上没有消息)之外,组件内部的一切都很好。

\n

我阅读了Watchers 的文档以及对有关观看道具的问题的答复(其中一个答复几乎与我所做的相同),但我只是无法理解为什么这在我的情况下不起作用。

\n

watch vue.js vue-props vuejs3

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