Home >Web Front-end >Vue.js >An article explaining in detail how vue implements v-model (with code examples)
This article brings you relevant knowledge about vue. It mainly introduces to you why we use v-model? How to use vue to implement v-model? If you are interested, let’s take a look. I hope it will be helpful to everyone.
v-model mainly provides two functions. The input value of the view layer affects the attribute value of the data. If the value of the data attribute changes, the view will be updated. The value of the layer changes.
The core is that on the one hand, the modal layer hijacks each attribute through defineProperty, and once changes are detected, it is updated through the relevant page elements. On the other hand, by compiling the template file, the input event is bound to the v-model of the control, so that the page input can update the relevant data attribute values in real time.
<template> <div id="app"> {{username}} <br/> <my-input type="text" v-model="username"></my-input> </div> </template> <script> import myinput from './components/myinput' export default { name: 'App', components:{ myinput }, data(){ return { username:'' } } } </script>
<template> <div class="my-input"> <input type="text" class="my-input__inner" @input="handleInput"/> </div> </template> <script> export default { name: "myinput", props:{ value:{ //获取父组件的数据value type:String, default:'' } }, methods:{ handleInput(e){ this.$emit('input',e.target.value) //触发父组件的input事件 } } } </script>
<template> <div> <kmDialog v-model="showDialog" > <el-button @click="show">点我</el-button> </div> </template> <script> import kmDialog from 'KmDialog.vue' export default { components: { KmDialog } data () { return { showDialog: false } }, methods: { show() { this.showDialog = true } } } </script>
<template> <el-dialog :title="isEdit ? '编辑设备' : '新增设备'" :visible.sync="value" width="40%" @close="cancel" > <span>这是一段信息</span> </el-dialog> </template> <script> export default { props: { value: { default: false, type: Boolean } }, methods: { cancel() { this.$emit('input', false) } } } </script>
Recommended learning: "vue.js Video Tutorial"
The above is the detailed content of An article explaining in detail how vue implements v-model (with code examples). For more information, please follow other related articles on the PHP Chinese website!