­

Vue自定義組件之v-model的使用

自定義組件之v-model的使用

v-model的語法糖可以為下面v-bind && @input聯合完成:

<input v-model="text">
<!-- 以上相當於如下寫法 -->
<input :value="text" @input="text=$event.target.value">

父子組件通訊的時候,可在父組件的孩子組件上面使用v-model,默認觸發子組件指定的event和prop接受參數

父組件:

<template>
  <div id="father">
    <p>{{ text }}</p>
    <child v-model="text"></child>
  </div>
</template>

<script>
import child from "./child.vue";
export default {
  name: "father",
  components: { child },
  data: function () {
    return {
      text: "我是父組件",
    };
  }
}
</script>

<style lang="less" scoped></style>

子組件:

<template>
  <div id="child">
    <p>{{ msg }}</p>
    <button @click="btnClick">點擊改變父組件內容</button>
  </div>
</template>

<script>
export default {
  name: 'child',
  model: {
    prop: "msg",
    event: "respond",
  },
  props: {
    msg: {
      type: String,
    },
  },
  methods: {
    btnClick() {
      this.$emit("respond", "我是子組件");
    },
  },
};
</script>

<style lang="less" scoped></style>

注意:在組件上使用v-mode時,其被使用組件上應該有個model對象配置,用於接受v-model傳遞過來的資訊,它有兩個屬性,prop是要指定傳過來的屬性接收參數,event是v-model時要指定綁定的事件名(由當前被使用組件定義)。

以上example中父組件上的 v-model 會把 msg用作 prop 且把 respond用作 event。這樣就可以實現父子組件之間的通訊,子組件可以拿到父組件傳過來的值,子組件也可以更改值。