vue.js 如何使用标记和v-model将数据传递给子组件< input>

zu0ti5jz  于 2023-06-06  发布在  Vue.js
关注(0)|答案(1)|浏览(173)

我试图从父组件传递值到子组件,如下面发布的代码所示。子组件中将接收从父组件传递的值的属性被绑定到v-model,如下面的代码所示。

<input :value="refInputModel"
         @input="refInputModel = $event.target.value"/>
</div>

我在代码运行时所期望的是,当按钮counterFunc被点击时,值changed如下所示:

refInputModel.value = "changed"

将传递给<input>上设置的子组件,但这不会发生
请让我知道如何从父组件中传递值到<input>标签中的子组件中的v-model

应用程序

<template>
  <img alt="Vue logo" src="./assets/logo.png">

  <div>
  <button @click="counterFunc">methodHandler</button>
  <hello-world :refInputModel='refInputModel'/>
  
</div>
</template>

<script> 
export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<script setup> 
import HelloWorld from './components/HelloWorld.vue'
import {ref,defineProps} from 'vue' 

const props = defineProps(['inputModel_'])
let refInputModel = ref(props.inputModel_)

const counterFunc = ()=> {
  refInputModel.value = "changed"
}
</script>

HelloWorld

<template>
  <div class="hello">
  <input :value="refInputModel"
         @input="refInputModel = $event.target.value"/>
  </div>
  
</template>

<script>
export default {
  name: 'HelloWorld',
}
</script>

<script setup> 
import { defineProps, ref} from 'vue'

const props= defineProps(['inputModel'])
let refInputModel = ref(props.inputModel)

onUpdated(()=>{
    console.log("HelloWorld.onUpdated");
    console.log("refInputModel:",refInputModel.value);
})
</script>
wz3gfoph

wz3gfoph1#

应用程序

<template>
  <img alt="Vue logo" src="./assets/logo.png">

  <div>
  <button @click="counterFunc">methodHandler</button>
  <hello-world :modelValue='refInputModel'
                @update:modelValue="newValue => refInputModel = newValue"/>
  
</div>
</template>

<script> 
export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<script setup> 
import HelloWorld from './components/HelloWorld.vue'
import {ref,defineProps} from 'vue' 

const props = defineProps(['inputModel_'])
let refInputModel = ref(props.inputModel_)

const counterFunc = ()=> {
  refInputModel.value = "changed"
}
</script>

HelloWorld

<template>
  <div class="hello">
  <input :value="modelValue"
     @input="$emit('update:modelValue', $event.target.value)"/>
</div>
  
</template>

<script>
export default {
  name: 'HelloWorld',
}
</script>

<script setup> 
import { defineProps, ref} from 'vue'

defineProps(['modelValue'])
defineEmits(['update:modelValue'])

onUpdated(()=>{
  console.log("HelloWorld.onUpdated");
  console.log("modelValue:",props.modelValue);
})
</script>

相关问题