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);
}
// ...
相關文章
相關標籤/搜索