你能够用 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>