記事ディレクトリ
序文
この記事は、以前の記事「Vue コンポーネントのネストの理解と mixin の使用」に基づいています。
包括父==>子传值 子==>父传值 兄弟组件传值
1. コンポーネント構造を確立する
1.図に示すように、student と school の 2 つの兄弟コンポーネントがアプリで管理されます。
2. 通信方法
1. 親コンポーネントが値を子コンポーネントに渡します。
①. 親コンポーネント App.vue にサブコンポーネントの Student タグを記述します。コードは次のとおりです。
<student name2="李四" :age2="18" />
②. Student コンポーネントは props オブジェクトを通じて以下を受け取ります。
//绑定方法:
<button @click="get_AppInfo">获取父组件传来的值</button>
//加入props配置项:
props: {
name2: {
type: String,
required: true,
},
age2: {
type: Number,
required: true,
},
}
//methods:
get_AppInfo() {
console.log("从父组件传来:", this.name2, this.age2);
}
③. 結果:
2. 子コンポーネントは値を親コンポーネントに渡します。
1. $refメソッド
①. 親コンポーネント App.vue にサブコンポーネントの school タグを書きます、コードは次のとおりです。
<school ref="xuexiao" />
//在mounted钩子中加入
this.$refs.xuexiao.$on("SoF", (data) => {
console.log("我是App容器,收到来自子组件的信息:", data);
});
②.studentコンポーネントは、this.$emitを介してオブジェクトの受信をトリガーします。
//绑定方法:
<button @click="send_AppInfo">发送信息给父组件</button>
//methods:
send_AppInfo(name) {
this.$emit("SoF", this.name);
},
③. 結果:
2. v-onバインディングイベントメソッド
①. 親コンポーネント App.vue にサブコンポーネントの school タグを書きます、コードは次のとおりです。
//对school组件标签改为:
<school v-on:SoF2="getXuexiaoInfo" />
//在methods中加入
getXuexiaoInfo(area) {
this.msg = area;
console.log("我是App容器,收到来自school组件的信息:", area); }
②.school コンポーネントは this.$emit を通じてオブジェクトの受信をトリガーします。
//绑定方法(v-on方式):
<button @click="send_AppInfo2">发送地区给父组件</button>
//methods:
send_AppInfo2(area){
this.$emit("SoF2", this.area);
},
③. 結果: v-on ボタンをクリックします。
3. 兄弟コンポーネント間で値を転送する
1. グローバルイベントバス $bus
①.mainjsでグローバルイベントバス$busをバインドする
new Vue({
components: {
school,
},
render: (h) => h(App),
beforeCreate() {
// 构造一个傀儡$bus来实现兄弟组件通信
// 安装全局事件总线
Vue.prototype.$bus = this;
},
}).$mount("#app");
②. 学生コンポーネントに情報を送信する学校を設定します。学校コンポーネントコード:
//绑定方法:
<button @click="send_SchoolInfo">school组件发送信息到student组件</button>
//methods:
send_SchoolInfo(age) {
this.$bus.$emit("bro", this.name);
},
③.studentコンポーネント設定オブジェクト受信:
//在mounted钩子中加入
this.$bus.$on('bro',(data)=>{
console.log("收到来自兄弟组件school的信息:",data)
})
③. 結果:
要約する
すべてのコンポーネント間の通信は、グローバル イベント バスを通じて実現できます。ただし、使用後にイベントをバインド解除する、つまりコンポーネントを破棄する前にバインドを解除することに注意する必要があります。