Vue父子组件v-model传值(子直接修改父,子能拿到父)

Vue3

父组件

<template>
  <div class="container">
    <SideInput v-model:inputValue="inputValue"></SideInput>
    {{ inputValue }}
  </div>
</template>

<script setup>
import SideInput from "./side-input.vue";
import { ref } from "vue";

const inputValue = ref("1");
</script>
<style lang="stylus" scoped>
.container
  color: #000
  text-align: center
  padding-top: 100px
</style>

子组件

<template>
  <div class="box">
    <input type="text" v-model="inputValue" @input="isInput" />
  </div>
</template>
<script setup>
import { ref, defineProps, defineEmits } from "vue";
const props = defineProps({
  inputValue: {
    type: String,
    required: "",
  },
});
const emit = defineEmits(["update:inputValue"]);
const isInput = (e) => {
  emit("update:inputValue",e.target.value);
};</script>
<style lang="stylus" scoped>
.box{
    font-size 20px
    color #000
}
</style>

Vue2

父组件

<template>
  <div>
    <Isinput v-model="inputDate"></Isinput>
    {{ inputDate }}
  </div>
</template>
<script>
import Isinput from "./isinput.vue";
export default {
  components: { Isinput },
  data() {
    return {
      inputDate: "989989",
    };
  },
};
</script>

子组件

<template>
  <div>
    <input type="text" v-model="inputValue" @input="change_" />
  </div>
</template>

<script>
export default {
  props: {
    value: { type: String },
  },
  data() {
    return {
      inputValue: this.value,
    };
  },
  mounted() {
    console.log(this.value);
  },
  methods: {
    change_(e) {
      this.$emit("input", e.target.value);
    },
  },
};
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容