vue.js父子組件傳參的原理與實現(xiàn)方法 原創(chuàng)
在Vue中,父子組件之間的數(shù)據(jù)傳遞常常會使用props進行實現(xiàn)。具體原理是,當(dāng)一個父組件嵌套了一個子組件時,在子組件內(nèi)部使用props接收從父組件傳遞過來的數(shù)據(jù),這些數(shù)據(jù)可以是基礎(chǔ)類型如字符串、數(shù)字等,也可以是對象或者數(shù)組等復(fù)雜類型。
下面展示一個例子,通過一個簡單的計數(shù)器組件Counter.vue,演示如何在父組件App.vue中傳值到子組件Counter.vue并更新計數(shù)器操作:
子組件:
<!-- Counter.vue -->
<template>
? <div class="counter">
? ? <h4>{{ title }}</h4>
? ? <p>當(dāng)前計數(shù):{{ count }}</p>
? ? <button @click="addCount">+1</button>
? ? <button @click="reduceCount">-1</button>
? </div>
</template>
<script>
export default {
? name: "Counter",
? props: {
? ? title: {
? ? ? type: String,
? ? ? required: true,
? ? },
? ? count: {
? ? ? type: Number,
? ? ? required: true,
? ? },
? },
? methods: {
? ? // 添加計數(shù)
? ? addCount() {
? ? ? this.$emit("add-count");
? ? },
? ? // 減少計數(shù)
? ? reduceCount() {
? ? ? this.$emit("reduce-count");
? ? },
? },
};
</script>父組件:
<!-- App.vue -->
<template>
? <div class="container">
? ? <h2>計數(shù)器應(yīng)用</h2>
? ? <hr />
? ? <!-- 父組件傳遞計數(shù)器標(biāo)題和當(dāng)前計數(shù)給子組件 -->
? ? <Counter :title="title" :count="count" @add-count="handleAddCount" @reduce-count="handleReduceCount" />
? </div>
</template>
<script>
import Counter from "./components/Counter.vue";
export default {
? name: "App",
? components: {
? ? Counter,
? },
? data() {
? ? return {
? ? ? title: "計數(shù)器",
? ? ? count: 0,
? ? };
? },
? methods: {
? ? // 添加計數(shù)
? ? handleAddCount() {
? ? ? this.count++;
? ? },
? ? // 減少計數(shù)
? ? handleReduceCount() {
? ? ? this.count--;
? ? },
? },
};
</script>在上述示例中,傳遞數(shù)據(jù)的方式是通過在父組件中使用v-bind指令將數(shù)據(jù)綁定到子組件的props屬性上,并在子組件內(nèi)部訪問props接收數(shù)據(jù)。同時,在子組件內(nèi)部定義了兩個方法addCount和reduceCount,用于觸發(fā)自定義事件,從而向父組件emit事件。
最后需要注意的是,父子組件之間的數(shù)據(jù)流是單向的,即數(shù)據(jù)只能從父組件流向子組件,不能反過來。如果子組件想要修改數(shù)據(jù),必須通過emit事件來通知父組件進行相應(yīng)的操作。
相關(guān)文章
vue中如何使用lodash的debounce防抖函數(shù)
防抖函數(shù) debounce 指的是某個函數(shù)在某段時間內(nèi),無論觸發(fā)了多少次回調(diào),都只執(zhí)行最后一次,在Vue中使用防抖函數(shù)可以避免在頻繁觸發(fā)的事件中重復(fù)執(zhí)行操作,這篇文章主要介紹了vue中使用lodash的debounce防抖函數(shù),需要的朋友可以參考下2024-01-01
Vant的Tabbar標(biāo)簽欄引入自定義圖標(biāo)方式
這篇文章主要介紹了Vant的Tabbar標(biāo)簽欄引入自定義圖標(biāo)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
vue項目打包解決靜態(tài)資源無法加載和路由加載無效(404)問題
這篇文章主要介紹了vue項目打包,解決靜態(tài)資源無法加載和路由加載無效(404)問題,靜態(tài)資源無法使用,那就說明項目打包后,圖片和其他靜態(tài)資源文件相對路徑不對,本文給大家介紹的非常詳細,需要的朋友跟隨小編一起看看吧2023-10-10
Vue引用vee-validate插件表單驗證問題(cdn方式引用)
這篇文章主要介紹了Vue引用vee-validate插件表單驗證問題(cdn方式引用),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12

