Vue双向数据绑定

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

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

  • 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>

案例:this

<!--子组件-->
<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>

相关文章
相关标签/搜索