vue 實現,子組件向父組件 傳遞數據
阿新 • • 發佈:2019-01-18
borde 個數 const pre 單擊 == code 接受 port
首先理清組件之間的關系
組件與組件之間,還存在著不同的關系。父子關系與兄弟關系(不是父子的都暫稱為兄弟吧)。
父子組件
父子關系即是組件 A 在它的模板中使用了組件 B,那麽組件 A 就是父組件,組件 B 就是子組件。
先寫子組件:
綁定一個單擊事件
<el-button type="primary" icon="el-icon-search" @click="search" style="background: #5b6270; border: none;">搜索</el-button>
定義數組:用來存值,然後傳遞給父組件
export default {
data() {
return {
childByValue:[] //先定義一個數組
};
}
}
methods: {
search: function() {
const inp = this.input;
if (inp ==="") {
this.selectAll(); //如果為空 則執行selectAll去
} else {
this.$axios.get(‘http://localhost:9999/search?productName=‘ + inp).then(res => {
if (res.data === "error") {
alert("抱歉,沒有查詢到你需要的商品");
} else {
this.childByValue = res.data; //給數組賦值
this.$emit(‘childByValue‘, this.childByValue) //發射、廣播出去 主要這裏
}
})
}
}
}
然後子組件就寫完了
父組件:
使用components 翻譯就是:組成的意思
import headers from ‘./Head.vue‘ //導入子組件
export default {
components: {
headers: headers //這裏是import 導入的名字一致
}
}
使用子組件
<headers @childByValue="childByValue"></headers>
截圖:
另外 還需要綁定事件來接受數據
methods: {
childByValue(value) {
console.log(value);//接收子組件的數據然後你想幹嘛就幹嘛
}
}
vue 實現,子組件向父組件 傳遞數據