javascript - 为什么 Vue 组件不会在选择更改时更新

标签 javascript vue.js vuejs2 vue-component

我有一个表单,可以在更改选择框时更改VUE组件中的某些文本。我在 jsfiddle 中创建了一个高度最小化的版本来显示我遇到的问题:

https://jsfiddle.net/ywaug7ft/

HTML:

<div id="app">
<h5>Select a gender</h5>
  <select v-model="gender">
    <option disabled="disabled" value>Select...</option>
    <option value="1">Male</option>
    <option value="2">Female</option>
    <option value="3">Couple</option>
  </select>
  <div></div>
  <detail-component v-for="(detail, index) in details" :data="detail" :index="index"></detail-component>

  {{details}}
</div>

<template id="details">
   <div>
     <h4><span v-if="item.gender == 3 && index == 0">Her</span><span
                v-else-if="item.gender == 3 && index == 1">His</span><span v-else>Your</span> Health Details</h4>
     <div>Index: {{index}}</div>
     <div>Gender: {{item.gender}}</div>
   </div>
</template>

View :

Vue.component('detail-component', {
  template: '#details',
  props: ['data', 'index'],
  data() {
    return {
      item: {
        gender: this.data.gender
      }
    }
  }
});

var app = new Vue({
  el: '#app',
  data: {
    gender: '',
    details: [],
    options: {
        gender: {
        "1": "Single Female",
        "2": "Single Male",
        "3": "Couple"
      }
    }
  },
  watch: {
    gender: function(val) {
      this.details = [];
      if (val == 1) {
        this.details.push({gender: 1});
      } else if (val == 2) {
        this.details.push({gender: 2});
      } else if (val == 3) {
        this.details.push({gender: 3}, {gender: 3});
      }
    }
  }
});

基本上,当我从下拉列表中选择 femalemale 时,我的 vue 组件应该更新 h 标签以显示 Your Details。当我选择 couple 时,我的 View 组件应该更新为 Her DetailsHis Details。但是,它不会将第一个索引更新为 Her,而是维护 Your

看看 jsfiddle,您就会明白我的意思。

只是想了解我做错了什么。我认为使用 watcher 会在组件中产生 react 。

最佳答案

如果 prop 值正在更新,你不会在 child 内部观察。
因此,每当 prop data 发生变化时,您都需要在子组件中对其进行watch

观看Fiddle ,

watch:{
  data(val){
    this.item.gender=val.gender
  }
}

或计算属性 Fiddle .

computed:{
  item(){
    return this.data;
  }
}

关于javascript - 为什么 Vue 组件不会在选择更改时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51992261/

相关文章:

javascript - AJAX 调用忽略表单验证

linux - 我的 nuxt 应用程序在 CodeSandbox 上运行良好,但在我的本地机器上运行不正常

javascript - 使用 Vue.js 过滤列表

typescript - nuxt3 自定义类型的简单指南

vue.js - 如何使用Vue transition 来扩展和收缩一个div

javascript - 垂直循环 HTM5 Canvas 中的图像数据

javascript - 比较两个数组并在相同值索引处更改数据

javascript - jQuery: .text() 被延迟

jquery - v-model 不会检测 jQuery 触发事件所做的更改

vue.js - Vue-CLI 组件错误 : You are using the runtime-only build of Vue where the template compiler is not available