vue input 使用v-model想要改变父属性的写法

直接在子组件使用v-model=“props传递的父属性”是会爆出警告的,也不符合vue 的设计思想,所以可以如下写法:

父组件:

<template>
  <div>
    <Test1 :curVal="val" @change-val="setVal"/>
  </div>
</template>

<script>
import Test1 from "@/components/Test1.vue";
export default {
  name: "Home",
  data() {
    return {
      val:''
    };
  },
  components: {
    Test1
  },
  methods:{
    setVal(val){
      this.val=val;
    }
  }
};
</script>

<style lang="less" scoped>
</style>

子组件:

<template>
  <div>
    <el-button type="success">成功按钮</el-button>
    <br>
    <el-input v-model="val" @input="changeVal" placeholder="请输入内容"></el-input>
  </div>
</template>

<script>
export default {
  name:'Test1',
  props:['curVal'],
  data(){
    return {
      val:''
    }
  },
  methods:{
    changeVal(val){
      this.$emit('change-val',this.val)
    }
  }
};
</script>

<style lang="less" scoped>
</style>

这里用到了elementui 想要运行代码的同学可以下载一下编译后使用

原文地址:https://www.cnblogs.com/llcdbk/p/12613362.html