1.父組件把方法傳遞給了子組件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
<ul>
<school v-for="item,index in schoolList" :action="changeEvent" :key="'abc'+index" :index='index'
:school-name="item"></school>
<h3>你選擇的學校是:{{chooseSchool}}</h3>
</ul>
</div>
<script>
Vue.component("school", {
props: ['schoolName', 'index', 'action'],
template: `
<li>
<h3>{{index}}-學校名稱:{{schoolName}}</h3>
<button @click="chooseEvent(schoolName)">選擇學校</button>
</li>
`,
methods: {
//把參數傳給父組件
chooseEvent: function (schoolName) {
this.action(schoolName)
}
}
})
let app = new Vue({
el: "#app",
data: {
schoolList: ['清華', '北大', '浙大', "中大"],
chooseSchool: ""
},
methods: {
changeEvent: function (data) {
//console.log("觸發學校選擇事件")
console.log(this)
this.chooseSchool = data
}
}
})
</script>
</body>
</html>
-
changeEvent可以改變chooseSchool的值,不知道哪個子組件調用,也不知道子組件的值是多少?
-
我們在組件中定義一個方法!這個方法寫在組件的methods里面。
<button @click="chooseEvent(schoolName)">選擇學校</button>
- 我們在methods方法調用參數里面的action,來把子組件數值傳給父組件
methods: {
//把參數傳給父組件
chooseEvent: function (schoolName) {
this.action(schoolName)
}
}
-
所以必須在參數列表props中定義一個action
props: ['schoolName', 'index', 'action'], -
然后在school標簽中把action綁定父組件app中的changeEvent方法
:action="changeEvent"
2.更簡單的方法$parent
直接在子組件通過this.$parent.changeEvent(schoolName)來調用
1.通過$parent來調用父組件,可以獲取父組件的方法,屬性等全部數據
2.當操作邏輯簡單的時候,就可以直接用$parent.方法
也可以使用$parent.屬性來使用
<button @click="$parent.chooseSchool=schoolName">選擇學校</button>
<button @click="$parent.changeEvent(schoolName)">選擇學校</button>
<button @click="$root.changeEvent(schoolName)">選擇學校</button>
但是不推薦這么寫,這樣寫的耦合程度太高了
3.獲取當前組件的根組件$root
建議使用props屬性來修改,這樣可以減少耦合,不推薦這種直接修改的方法
