在 Vue2 中,我試圖訪問子組件的資料,然后在不觸發事件的情況下放入父組件的資料。在下面的例子中,我想將 count:20 保存到父組件中,如果有任何錯誤,請告訴我,謝謝!
子組件
<template>
<div></div>
</template>
<script>
export default {
data() {
return {
count: 20,
};
},
};
</script>
父組件
<template>
<div>
<child ref="child1"></child>
{{count}}
</div>
</template>
<script> import child from './child.vue'
export default {
components: {
child
},
data() {
return{
count:this.$refs.child1.count
}
},
}
</script>
VScode 中的警告訊息
型別 'Vue | 中不存在屬性 'count' 元素 | Vue[] | 元素[]'。“Vue”型別上不存在屬性“count”。
瀏覽器中的警告訊息
[Vue 警告]:data() 中的錯誤:“TypeError: undefined is not an object (evaluating 'this.$refs.child1')”
uj5u.com熱心網友回復:
讓我先介紹一下我建議按預期使用 Vue 框架。因此,應該$emit使用 vuex 存盤或使用 vuex 存盤來完成將資料從子級傳遞給父級的集中狀態管理。
有了這個,您將要等到安裝父組件以設定count資料屬性。
孩子
<template>
<div></div>
</template>
<script>
export default {
data() {
return {
count: 20,
};
},
};
</script>
家長
<template>
<div>
<child ref="child1"></child>
{{ count }}
</div>
</template>
<script>
import Child from "./components/Child";
export default {
components: {
Child
},
data() {
return{
count: 0
}
},
mounted () {
this.count = this.$refs.child1.count
}
};
</script>
這會起作用,但它不會是被動的。這一切都可以大大簡化,并通過以下更改做出反應:
孩子
<template>
<div></div>
</template>
<script>
export default {
data() {
return {
count: 20,
};
},
watch: {
count (currentValue) {
this.$emit('update', currentValue);
}
},
beforeMount () {
this.$emit('update', this.count)
}
};
</script>
家長
<template>
<div>
<child @update="count = $event"></child>
{{ count }}
</div>
</template>
<script>
import Child from "./components/Child";
export default {
components: {
Child
},
data() {
return{
count: 0
}
}
};
</script>
顯示作業示例的快速鏈接:https : //codesandbox.io/s/interesting-kalam-et0b3?file=/src/App.vue
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/380337.html
上一篇:Nuxt存盤getter不起作用,賦予有效載荷的ID不是整數 錯誤:[vuex]不要在突變處理程式之外改變vuex存盤狀態
