父组件把方法传递给了子组件
<!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"