Vue双向数据绑定

耗尽温柔 提交于 2021-02-17 02:05:19

你可以用 v-model 指令在表单 <input><textarea><select> 元素上创建双向数据绑定。它会根据控件类型自动选取正确的方法来更新元素。尽管有些神奇,但 v-model 本质上不过是语法糖。它负责监听用户的输入事件以更新数据,并对一些极端场景进行一些特殊处理。

v-model 会忽略所有表单元素的 value、checked、selected attribute 的初始值而总是将 Vue 实例的数据作为数据来源。你应该通过 JavaScript 在组件的 data 选项中声明初始值。

  • text 和 textarea 元素使用 value property 和 input 事件;
  • checkbox 和 radio 使用 checked property 和 change 事件;
  • select 字段将 value 作为 prop 并将 change 作为事件。

绑定数据:

<input v-model="message" placeholder="edit me">
<p>Message is: {{ message }}</p>

案例:

<!--子组件-->
<template>
    <div>
        <!--绑定数据-->
        <input v-model="rumenz" />
        <span>
            {{rumenz}}
        </span>
        <button @click="cleanVal">清除数据</button>
    </div>
</template>
<script>
export default{
    //将函数声明成一个属性
    props:['cleanVal1'],
    data(){
        return{
           rumenz:"入门小站"
        }
    },
    methods: {
       cleanVal(){
           this.rumenz="";
       }
    }
}
</script>

<!--父组件-->

<template>
<div id="app">
   {{msg}}
   <button @click="cleanVal">父组件清空</button>
   <!--将子组件的cleanVal1的函数变量绑定到cleanVal函数上-->
   <ModelBind ref="child" :cleanVal1="cleanVal"/>
  
</div>
</template>

<script>
import ModelBind from "./components/ModelBind"

export default {
  name: 'App',
  data() {
        return {
            msg: "hello 入门小站"
        }
    },
    methods: {
      cleanVal(){
         //父组件操作子组件的函数
         this.$refs.child.cleanVal();
      }
       
    },
  components: {
    ModelBind  //必须声明
  }
}
</script>

<style>

</style>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!