簡體   English   中英

將數據從父組件傳遞到子組件時,為什么我不能將數據綁定到我的 v-model?

[英]Why cant i bind data to my v-model when passing data from parent to child component?

我想將數據從父組件傳遞到子組件,並通過 v-model 將數據綁定到輸入字段,以在父組件中顯示來自 api 調用的數據。 但是綁定到輸入字段時似乎有問題我收到此錯誤消息: Unexpected mutation of "data" prop.eslintvue/no-mutating-props

父組件

<script lang="ts">
import { defineComponent,ref } from 'vue';
import axios from 'axios'
import ChildComponent from '../components/ChildComponent.vue';

export default defineComponent({
    Component: { ChildComponent },
    name: 'IndexPage',
    setup() {
        return {
            fixed: ref(false),
            data: []
        };
    },
    mounted() {
        this.getData();
    },
    methods: {
        getData() {
            axios.get('/api/Hotel/' + 2).then((response) => {
                this.data = response.data;
                this.fixed = true,
                    console.log(this.data);
            });
        }
    },
    components: { ChildComponent }
});

</script>

子組件

<template>
    <main>
        <q-card class="height: 500px; width: 500px">
      <q-card-section>
        <div class="text-h6">Terms of Agreement</div>
        <div class="q-pa-md">
    <div class="q-gutter-md" style="max-width: 300px">
      
    <div>
                <q-input filled v-model="data.message" label="Filled" />

    </div>

    </div>
  </div>
      </q-card-section>

      <q-separator />

      <q-separator />

      <q-card-actions align="right">
        <q-btn flat label="Decline" color="primary" v-close-popup />
        <q-btn flat label="Accept" color="primary" v-close-popup />
      </q-card-actions>
    </q-card>

    </main>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';

export default defineComponent({
    props:['data'],
    name: 'ChildComponent',
    setup() {
        return {
            text: ref(''),
        };
    },

});


</script>

我試過這樣在我的子組件中制作安裝方法,如下所示:


    <div>
       <q-input filled v-model="dataIn.message" label="Filled" />

    </div>

export default defineComponent({
    props:['data'],
    name: 'ChildComponent',
    setup() {
        return {
            text: ref(''),
            dataIn:{}
        };
    },

    mounted(){
    this.dataIn = this.data
    },
});

它似乎有效但不是最佳的,刷新頁面時我丟失了數據。 有人有解決方案嗎?

道具應該只讀。 您的dataIn方法需要一個觀察者,它會在您的data屬性更改時更新您的dataIn

選項API:

export default defineComponent({
props:['data'],
name: 'ChildComponent',
data() {
   text: '',
   data: this.dataIn,
}

watcher: {
   dataIn: (newValue,oldValue){
      this.data = newValue
   }
}

});

如果我理解正確的話,你需要從 child 發出事件或者將計算屬性與 getter/setter 一起使用:

 const { ref, onMounted, watch } = Vue const app = Vue.createApp({ setup() { const items = ref({}) const getData = () => { items.value = ({id: 1, message: 'aaa'}) /*axios.get('/api/Hotel/' + 2).then((response) => { this.data = response.data; this.fixed = true, console.log(this.data); });*/ } onMounted(async() => await getData()) // react to chenges from child const changed = (val) => { items.value.message = val.message } return { //fixed: ref(false), items, changed }; }, }) app.component('ChildComponent', { template: ` <main> <q-card class="height: 500px; width: 500px"> <q-card-section> <div class="text-h6">Terms of Agreement</div> <div class="q-pa-md"> <div class="q-gutter-md" style="max-width: 300px"> <div> <.-- listen to updating --> <q-input filled v-model="text:message" @update,model-value="change" label="Filled" /> </div> </div> </div> </q-card-section> <q-separator /> <q-separator /> <q-card-actions align="right"> <q-btn flat label="Decline" color="primary" v-close-popup /> <q-btn flat label="Accept" color="primary" v-close-popup /> </q-card-actions> </q-card> </main> `: props,['items'], setup(props. {emit}) { const text = ref(props,items) // emit event with changed value const change = () => { emit('changed'. text.value) } // watch for the props changes watch( () => props,items, (newValue. oldValue) => { text;value = newValue; } ), return { text; change }, }. }) app.use(Quasar) app.mount('#q-app')
 <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet" type="text/css"> <link href="https://cdn.jsdelivr.net/npm/quasar@2.5.5/dist/quasar.prod.css" rel="stylesheet" type="text/css"> <div id="q-app"> {{items}} <:-- listen to child event --> <child-component:items="items" @changed="changed"></child-component> </div> <script src="https.//cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod:js"></script> <script src="https.//cdn.jsdelivr.net/npm/quasar@2.5.5/dist/quasar.umd.prod.js"></script>

似乎您想更改子組件上的數據,您必須使其雙向綁定。 您應該像這樣更改您的子代碼(您在組件中使用自定義 q-input 並且屬性可能略有不同,但它是相同的概念):

<q-input
        :value="value"
        v-bind="$attrs"        
        v-on="$listeners"
        @input="(v) => $emit('input', v)"
      />

而不是使用數據道具,你應該將它更改為值:

  props: {
    value: {
      type: [String], // multiple type also defenition accepted
      default: "",
    },
}

然后在您的父母中只需使用這樣的子組件:

<your-child-component v-model="someData" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM