javascript - Vue V-Model 启动损失选择 Selection

标签 javascript html vuejs2 html-select v-model

我在对某些类型的 html 元素初始化 Vue 时遇到问题,请查看以下代码:

new Vue({
  el: '#app',
  data: {
    test: ''
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  Without Vue:
  <!-- Non-Vue select defaults to selected value -->
  <select>
    <option>1</option>
    <option selected>2</option>
    <option>3</option>
  </select>

  <br /> 
  <br /> 
  
  With Vue:
  <!-- Vue enabled list loses selection -->
  <select v-model="test">
    <option>1</option>
    <option selected>2</option>
    <option>3</option>
  </select>
</div>

当我启动 Vue 时,您声明 v-Modal 的任何“选择”似乎都失去了它们的选择值。这如 the documentation 中所述:

v-model will ignore the initial value, checked or selected attributes found on any form elements. It will always treat the Vue instance data as the source of truth. You should declare the initial value on the JavaScript side, inside the data option of your component.

现在我可以做到这一点,但对于每个选择,我现在需要在 Vue 之外编写一些 JS 来填充/重新填充选择的默认值(通过填充“数据”属性,或重新选择先前选择的值后 Vue减速)。

有更简单的方法吗?也许我可以向 Vue 提供某种选项或标记以“保留”从 HTML 控件的初始状态继承的值?

最佳答案

利用vue的 react 系统,vue需要完全控制。所以没办法,只好通知vue以某种方式了解这些默认值。

如果您以 html 为中心,那么它会有点尴尬:您必须选择 dom元素找到它的默认值并将其设置回 vue .那行得通,但会很不合常理。

vue 中的正确方法就是完全数据驱动,根据数据构建HTML。例如,如果您的表单有 2 个选择框,则使用 vue这样,您应该为所有 option 定义数据如果你有,并使用这些数据从头开始生成这些元素(请注意,我在这里使用 Single File Component 格式):

<template>
  <div>
    <Select :items="list1"/>
    <Select :items="list2"/>
  </div>
</template>
<script>
import Select from './components/Select.vue';

export default {
  data() {
    return {
      list1: [
        { id: 1, name: "spoon" },
        { id: 2, name: "fork", preselect: true },
        { id: 3, name: "knife" }
      ],
      list2: [
        { id: 4, name: "macbook" },
        { id: 5, name: "dell" },
        { id: 6, name: "lenovo", preselect: true }
      ]
    };
  },
  components: { Select }
};
</script>

而且,这是 <Select> 的代码组件(请注意,这是一个自定义 Vue 组件,因为它以大写字母 S 开头)。该组件将接收 Prop items , 并根据给定的项目自动计算所选值:

<template>
  <select v-model="selected">
    <option 
      v-for="item of items"
      :key="item.id"
      :value="item.id">
        {{ item.name }}
    </option>
  </select>
</template>
<script>
export default {
  props: ["items"],
  data() {
    return {
      // pre-select item from 'items'
      selected: this.items.filter(item => item.preselect)[0].id
    };
  }
};
</script>

完成后,项目 fork和项目 lenovo将根据数据指示进行预选。您还可以在这个 codesandbox 上看到一个工作示例.

关于javascript - Vue V-Model 启动损失选择 Selection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52729627/

相关文章:

javascript - 如何在 google 闭包库上修复 sha256 hmac 的加密?

javascript - dropzone.js:如何重命名文件?

vue.js - 如何使用vue-draggable自动滚动功能

npm - 在其他设备上无法通过IP地址访问Vue项目 vue cli 3 npm

vuejs2 - Vue2 : is possible to pass multiple props to component?

javascript - 当一个 Canvas 放置在另一个 Canvas 之上时文本模糊

javascript - 3d.js(强制)- 获取工具提示链接上的当前鼠标位置

javascript - 根据 DOM-inspector,FORM 看起来是空的

JavaScript 未完成循环

Javascript fadeIn fadeOut 不断重新淡出(没有 JQuery!)