简体   繁体   English

如何在组件之间传递v-model值

[英]How to pass v-model value between components

I have a parent form component and a child. 我有一个父表单组件和一个孩子。 How do I pass data from one to another using v-model? 如何使用v-model将数据从一个传递到另一个? They are in different files . 它们位于不同的文件中 I'm using the components of the Quasar Framework. 我正在使用Quasar框架的组件。

Parent Component 父组件

<template>
  <q-input
    label="Nome *"
    lazy-rules
    :rules="[val => (val && val.length > 0) || 'Por favor, digite o seu nome']"
    v-model="nome"
  />
</template>

<script>
export default {
  name: "Nome",
  data() {
    return {
      nome: "Max"
    };
  }
};
</script>

Child Component 子组件

<template>
  <div class="q-pa-md" style="max-width: 500px">
  <q-form @reset="onReset" class="q-gutter-md">
      <Nome> </Nome>              
      <div>
   <q-btn label="Reset" type="reset" color="red" flat class="q-ml-sm" />
      </div>
    </q-form>
  </div>
</template>

<script>
import Nome from "components/Nome.vue";
export default {
  components: { Nome },  

  onReset() {
    this.name = null;
  }
};
</script>

How do I onReset() work? 我如何onReset()工作?

Automatically translated. 自动翻译。

I think you have some confusion about your child component and parent component. 我认为你对你的子组件和父组件有些困惑。 On your code Nome is the child component and the form that using Nome is the parent component. 在您的代码上, Nome是子组件,使用Nome的表单是父组件。

You can use ref to call the reset method on Nome from the parent form component. 您可以使用ref从父窗体组件调用Nome上的reset方法。

Here is a Working example - 这是一个工作示例 -

 Vue.component("nome-input", { data(){ return { input: "" } }, template: ` <input @input="onInput" type="text" v-model="input"> `, methods: { reset(){ this.input = "" }, onInput(){ this.$emit('onInput', this.input); } } }); Vue.component("user-form", { data(){ return { name: '', } }, components: { }, template: ` <div> {{name}} <nome-input ref="nome" @onInput="updateName"></nome-input> <button @click.prevent="save">Save</button> <button @click.prevent="reset">reset</button> </div> `, methods: { save(){ console.log(this.name); }, reset(){ this.name = ""; this.$refs.nome.reset(); }, updateName(value){ this.name = value; } } }); new Vue({ el: "#app", }) 
 body { background: #20262E; padding: 20px; font-family: Helvetica; } #app { background: #fff; border-radius: 4px; padding: 20px; transition: all 0.2s; } 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <user-form></user-form> </div> </body> </html> 

Here is a jsfiddle link for the above codes https://jsfiddle.net/azs06/u4x9jw62/34/ 以下是上述代码的jsfiddle链接https://jsfiddle.net/azs06/u4x9jw62/34/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM