1_01 vue的双向绑定

听说vue1是双向绑定,不过现在Vue2不能直接双向绑定,需要设置绑定。

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

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

二、利用prop和事件制作v-model

子组件

<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>

父组件

<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>

注意事项

  • 子组件内部是不能改变prop属性,只能通过父组件改变,再通过prop传递子组件,现在要想改变父组件值,只能通过emit。

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

如下面错误代码示例:

// ...
props: {
    value: ''
},
input () {
    // 这是错误的写法,
    this.value = !this.value;
    this.$emit('input', this.value);
}
// ...

猜你喜欢

转载自www.cnblogs.com/liangcheng11/p/9005882.html