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。这样就可以实现父子组件之间的通信,子组件可以拿到父组件传过来的值,子组件也可以更改值。

posted @ 2022-06-03 17:50  star*时光£裔℡  阅读(510)  评论(0编辑  收藏  举报