v-model-封装组件的好帮手

953 阅读1分钟

一、v-model的介绍 使用过vue的小伙伴对v-model都不会陌生的,当我们想要一个变量是响应式的变量,那么在平常的form表单中我们会使用它来绑定我们的变量,当input或者select下拉框的值变化时,我们绑定的变量的值也会跟着变化,这是因为使用v-model可以实现双向数据绑定,我们在组件封装的时候也可以使用它来达到我们想要的效果,废话不多说,直接上代码。 例如我们弹窗组件中有一个表单:

<template>
    <el-dialog
    title:'弹窗'  
   :visible.sync="isShowCreateDialog"
   :before-close="closeDialog">
   <label>姓名:</label> 
  <el-input   v-model="userInfo.name" />
  <label>电话:</label> 
  <el-input   v-model="userInfo.phone" />
     <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="createOrganName">确 定</el-button>
        </span>
   </el-dialog>
</template>
<script>
export default {
name:'UserDialog'
model: {
prop: 'user',
event: 'updateUser',
},
props: {
user: {
type: String,
},
data(){
return {
userInfo:this.user,//使用这个变量是为了不直接更改props的值
}
},
methods:{
updateUserInfo() {
   this.$emit('update:user', this.userInfo);
},
}
}
</script>

v-model 其实是一个语法糖来的 它是由v-bind和emit来封装而成的,那么我们当中有用到的一个model属性,这个值是可以用来自定义我们想要触发的方法,例如上面的更新user值的updateUser方法,其中我们还定义了一个变量userInfo,这个是为了避免直接修改props传过来的值,这个props的值是不允许直接修改的哦! 那么我们也是需要有触发user变更的方法,便于调用我们的emit方法把最新的值发射出去给我们的父组件,同时记住要用update:xxx,这个是关键,具体何原因,我改天再专门讲一下。 我们在父组件如何使用呢,贼简单,就下面一句代码搞定,舒舒服服就完事了 <UserDialog v-model="user"></UserDialog>

二、学习时间 2021.06.15 下午

三、收获 使用v-model来封装组件,可以让父组件代码看起来更整洁,而且也是很实在,可以把独立的东西抽离出来,便于后续的管理,美滋滋。