1_01 vue的双向绑定

据说vue1是双向绑定,不过如今Vue2不能直接双向绑定,须要设置绑定。javascript

1、常见的是input表单的v-model

const component = {
    template: `
        <div>
            <input v-model="value"> {{value}}
        </div>
    `
}

2、利用prop和事件制做v-model

子组件vue

<template>
  <button @click="input">
    <slot></slot>
  </button>
</template>
<script>
export default {
  props: {
    value: {
      default: false,
      type: Boolean,
    }
  },
  methods: {
    input () {
      this.$emit('input', !this.value);
    }
  }
}
</script>

父组件java

<template>
  <div>
    <TagButton v-model="isTagSelected">全选</TagButton>{{isTagSelected}}
  </div>
</template>
<script>
import TagButton from './tagButton';
export default {
  components: {
    InputText,
    TagButton,
  },
  data () {
    return {
      isTagSelected: false,
    }
  }
}
</script>

注意事项this

  • 子组件内部是不能改变prop属性,只能经过父组件改变,再经过prop传递子组件,如今要想改变父组件值,只能经过emit。双向绑定

  • v-model 是 :value@input 结合。code

以下面错误代码示例:component

// ...
props: {
    value: ''
},
input () {
    // 这是错误的写法,
    this.value = !this.value;
    this.$emit('input', this.value);
}
// ...
相关文章
相关标签/搜索