当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue组件实现v-model双向绑定

vue组件实现v-model双向绑定

2020年07月11日  | 移动技术网IT编程  | 我要评论

简单了解下v-model

Vue官网API: v2/api/#model.
自定义组件在使用 v-model 时定制 prop 和 event。

前提知识:Vue-处理边界情况 中的 emit、refs 和 Prop 单向数据流相关知识。

v-model原理

我们观看过Vue关于modelAPI的介绍之后大概知道了:

<my-input v-model="searchText" />

实际上等于:

<my-input
  :value="searchText"
  @change="val => {searchText = val}"
>

测试例子

首先是我们自定义的组件:

<template>
  <div class="hello">
    <h1>{{ message }}</h1>
    <button @click="toFather">send to father</button>
  </div>
</template>

<script>
  export default {
    name: 'HelloWorld',
    model: {
      prop: 'message',
      event: 'msgChange'
    },
    props: {
      message: String,
    },
    data() {
      return {
        msg: 'Welcome to Your Vue.js App (message to father)'
      }
    },
    methods: {
      toFather() {
        this.$emit("msgChange", this.msg);
      }
    }

  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

页面调用:

<template>
  <div>
    <hello-world v-model="mes"></hello-world>
    <button @click="toSon">send to son</button>
  </div>
</template>

<script>
  import HelloWorld from "../components/HelloWorld";

  export default {
    name: "test",
    data() {
      return {
        mes: "Send message to son"
      }
    },
    methods: {
      toSon() {
        this.mes = "Send message to son"
      }
    },
    components: {
      HelloWorld
    }
  }
</script>

<style scoped>

</style>

好了,一切准备就绪。我们在页面里面添加watch的方法,观察下v-model绑定的mes的变化:

watch: {
      mes(newMes, oldMes) {
        console.log("新值--------------->>>" + newMes);
        console.log("旧值--------------->>>" + oldMes);
      }
    },

首次加载页面,可以看到页面的值(mes)已经传给组件了。
在这里插入图片描述

接下来点击组件内的按钮 “send to father ”,将组件的值传回页面:
在这里插入图片描述
从watch的方法可以看出,组件的值已经传到了页面。

关于踩到的坑

刚开始写的时候,我直接把props的值给通过 emit 绑定回去了,结果导致了:
在这里插入图片描述
最后还是看了Vue的API才知道是prop问题。。

大概就这样,如若有错,请指出。谢谢。

本文地址:https://blog.csdn.net/qq_32628331/article/details/107248119

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网