1. 前提&知识点
1./components/Father.vue 是父组件, Son.vue 是子组件
2.子组件修改父组件
emit
2. 组件通信
1. 首先对子组件绑定一个事件 changeFatherTitle,用来修改父组件的标题
<li v-for="item in father_list" :key='item' @click="changeFatherTitle">{{item}}</li>
2. 添加changeFatherTitle方法
methods: { changeFatherTitle (ev) { console.log(this) } }
3. 添加自定义事件$emit 接收两个参数:第一个参数,自定义名称,第二个参数,自定义内容
methods: { changeFatherTitle (ev) { console.log(this) this.$emit('changeFatherTitle', ev.target.innerHTML) } }
4. 子组件已经触发了changeFatherTitle事件,父组件接收 father.vue ,在子组件标签上绑定changeFatherTitle事件
<son :father_list="father_list" @changeFatherTitle="changeTitle"></son>
5. 添加 changeTitle方法, 通过子组件获取的数据,每次点击修改父组件的title
methods: { changeTitle(str) { this.title = str; } }
6. 效果
3. 完整代码
Father.vue
<template> <div> <h2>{{title}}</h2> <son :father_list="father_list" @changeFatherTitle="changeTitle"></son> </div> </template> <script> import Son from "./Son.vue"; export default { name: "Father", data() { return { title: "father", father_list: ["第一章", "第二章", "第三章", "第四章"] }; }, methods: { changeTitle(str) { this.title = str; } }, components: { son: Son } }; </script>
Son.vue
<template> <div> <ul> <li v-for="item in father_list" :key='item' @click="changeFatherTitle">{{item}}</li> </ul> </div> </template> <script> export default { data () { name: 'Son' return { // list: ['第一章', '第二章', '第三章', '第四章'] } }, methods: { changeFatherTitle (ev) { console.log(this) this.$emit('changeFatherTitle', ev.target.innerHTML) } }, props: ['father_list'] } </script>