Vue父子組件相互傳值

1. 父組件向子組件傳值

  • 子組件在props中創建一個屬性,用以接收父組件傳過來的值
  • 父組件中註冊子組件
  • 在子組件標籤中添加子組件props中創建的屬性
  • 把需要傳給子組件的值賦給該屬性
<div id="app">
<input type="text" v-model="txtRoot">
<child :txt="txtRoot" @child="childChange"></child>
</div<script src="vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
txtRoot: "test"
},
components: {
child: {
template: "<p>{{txt}}</p>",
props: ["txt"]
}
}
})
</script>

2. 子組件向父組件傳值

  • 子組件中需要以某種方式例如input事件的方法來觸發一個自定義事件
  • 將需要傳的值作爲$emit的第二個參數,該值將作爲實參傳給響應自定義事件的方法
  • 在父組件中註冊子組件並在子組件標籤上綁定對自定義事件的監聽
<div id="app">
<input type="text" v-model="txtRoot">
<p>{{txtRoot}}</p>
<child @child="childChange"></child>
</div>
<script src="vue.js"></script>
<script type="text/html" id="child">
<div>
<input type="text" v-model="txtChild" @input="childEdit">
</div>
</script>
<script>
Vue.component("child", {
data() {
return {
txtChild: "";
}
},
template: "#child",
methods: {
childEdit() {
this.$emit("child", this.txtChild);
}
}
})
const app = new Vue({
el: "#app",
data: {
txtRoot: "text"
},
methods: {
childChange(txtChild) {
this.txtRoot = txtChild;
}
}
})
</script>

3. 父子組件相互傳值

例子效果:父組件和子組件中各有一個input標籤和一個p標籤,通過父組件或子組件中的input進行編輯,同步更改4個標籤的顯示內容。
<div id="app">
<input type="text" v-model="txtRoot">
<p>{{txtRoot}}</p>
<child :txt="txtRoot" @child="childChange"></child>
</div>
<script src="vue.js"></script>
<script type="text/html" id="child">
<div>
<input type="text" v-model="txtChild" @input="childEdit">
<p>{{txt}}</p>
</div>
</script>
<script>
Vue.component("child", {
data() {
return {
txtChild: this.txt
}
},
template: "#child",
methods: {
childEdit() {
this.$emit("child", this.txtChild);
}
},
props: ["txt"],
watch:{
txt(){
this.txtChild= this.txt;
}
}
})
const app = new Vue({
el: "#app",
data: {
txtRoot: "text"
},
methods: {
childChange(txtChild) {
this.txtRoot = txtChild;
}
}
})
</script>

4. vue的$emit(event,[...args])

  • 參數

    • {string} event
    • [...args]

    觸發當前實例上的事件。附加參數都會傳給監聽器回調。

      子組件通過$emit觸發父組件上綁定的自定義事件,將自身數據作爲參數傳入事件函數,在父組件的事件函數中將參數賦值給父組件的對應變量。

示例,App.vue中v-on爲組件綁定事件(自定義事件),子組件通過$emit觸發事件

//header.vue
<template>
<a class="t-btn" @click="showTools"></a>
</template>
export default{
methods: {
showTools(){
this.$emit('tools');
}
}
}
//App.vue
<template>
<n-header @tools="changePages"></n-header>
</template>
export default{
data(){
return{
tools:false,
table:false
}
},
methods:{
changePages(){
if(this.table){
this.table = !this.table;
}else{
this.tools = !this.tools
}
}
}
}
總結:無論是子組件向父組件傳值還是父組件向子組件傳值,他們都有一個共同點就是有中間介質,子向父的介質是自定義事件,父向子的介質是props中的屬性。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章