思路:分为两部分:父向子;子向父。
一、父组件向子组件传数据,用props
附带props命名规则:props中属性的命名规则_vue3 props 属性 别名_阿兵er的博客-CSDN博客
// 父组件
<template>
<div id="father">
<son :msg="msgData" :fn="myFunction"></son>
</div>
</template>
<script>
import son from "./son.vue";
export default {
name: father,
data() {
msgData: "父组件数据";
},
methods: {
myFunction() {
console.log("vue");
}
},
components: {
son
}
};
</script>
// 子组件
<template>
<div id="son">
<p>{{msg}}</p>
<button @click="fn">按钮</button>
</div>
</template>
<script>
export default {
name: "son",
props: ["msg", "fn"]
};
</script>
二、子组件向父组件传数据,用$emit
// 父组件
<template>
<div class="section">
<com-article :articles="articleList" @onEmitIndex="onEmitIndex"></com-article>
<p>{{currentIndex}}</p>
</div>
</template>
<script>
import comArticle from './test/article.vue'
export default {
name: 'comArticle',
components: { comArticle },
data() {
return {
currentIndex: -1,
articleList: ['红楼梦', '西游记', '三国演义']
}
},
methods: {
onEmitIndex(idx) {
this.currentIndex = idx
}
}
}
</script>
//子组件
<template>
<div>
<div v-for="(item, index) in articles" :key="index" @click="emitIndex(index)">{{item}}</div>
</div>
</template>
<script>
export default {
props: ['articles'],
methods: {
emitIndex(index) {
this.$emit('onEmitIndex', index) // 触发父组件的方法,并传递参数index
}
}
}
</script>
注:
1. 本文代码来源于「2021」高频前端面试题汇总之Vue篇 (上) - 掘金 (juejin.cn) - 三、(1)
2. 示例代码是Vue2的写法,现在项目逐渐以Vue3为主,附Vue3官方文档 简介 | Vue.js (vuejs.org)
【放在末尾~
面试时我答成了props和emit,回答得简陋且不全面,这个有必要总结一次】