vue-双向绑定

v-model

model 选项和 $emit 组合实现,然后便可在父组件直接使用 v-model 属性了。

示例

<template>
  <div>
    <label for="ref">
      <span class="label">{{ label }}</span>
      <select
        id="ref"
        :value="value"
        class="select"
        @change="$emit('changeSelect', $event.target.value)"
      >
        <option
          v-for="item in options"
          :key="item.value"
          :value="item.value"
        >
          {{ item.key }}
        </option>
      </select>
    </label>
  </div>
</template>

<script>
export default {
  name: 'Select',
  model: {
    value: {
      type: String,
      required: false,
      default: '',
    },
    event: 'changeSelect',
  },
  props: {
    options: {
      type: Array,
      required: true,
    },
    label: {
      type: String,
      required: false,
      default: '',
    },
    value: {
      type: String,
      required: false,
      default: '',
    },
  },
};
</script>

<style scoped>
@import "../../css/panel/select.css";
</style>

.sync

注意带有 .sync 修饰符的 v-bind 不能和表达式一起使用 (例如 v-bind:title.sync="doc.title + '!'" 是无效的)。
取而代之的是,你只能提供你想要绑定的属性名,类似 v-model。

示例

this.$emit("update:value", e.target.value)
<info :value.sync="myValue"></info>

当我们用一个对象同时设置多个 prop 的时候,也可以将这个 .sync 修饰符和 v-bind 配合使用:

<text-document v-bind.sync="doc"></text-document>

这样会把 doc 对象中的每一个属性 (如 title) 都作为一个独立的 prop 传进去,然后各自添加用于更新的 v-on 监听器。
将 v-bind.sync 用在一个字面量的对象上,例如 v-bind.sync=”{ title: doc.title }”,是无法正常工作的,因为在解析一个像这样的复杂表达式的时候,有很多边缘情况需要考虑。

posted @ 2020-01-16 11:39  qianbuhan  阅读(144)  评论(0)    收藏  举报