我们在编写vue组件的时候,不同组件之间,可能有很多相似之处,我们可以把这些相同的地方提取出来。
提取到一个js文件中,假设这个文件名叫 mixin.js
export const mixin = {
methods: {
showName() {
console.log(this.name);
alert(this.name)
}
}
}
在需要用到这个配置的vue文件中进行使用
<script>
import {mixin} from "@/components/mixin";
export default {
name: "Student",
props: {
name: {
type: String,
required: true
}
},
data() {
return {
msg: "Student"
}
},
mixins: [mixin],
}
</script>
<template>
<div>
<h1 @click="showName">学生姓名:{{ name }}</h1>
</div>
</template>
<style scoped>
div {
color: red;
font-size: 20px;
background-color: #ccc;
width: 800px;
height: 200px;
}
</style>
这样一来,我们的代码就更加精炼了