src_mixin(混入)
文章发布较早,内容可能过时,阅读注意甄别。
# 代码
# 代码路径
$ tree -N
.
├── App.vue
├── components
│ ├── School.vue
│ └── Student.vue
├── main.js
└── mixin.js
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# App.vue
<template>
<div>
<School />
<hr />
<Student />
</div>
</template>
<script>
import School from "./components/School.vue";
import Student from "./components/Student.vue";
export default {
name: "App",
components: { School, Student },
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# School.vue
<template>
<div>
<h2 @click="showName">学校名称:{{ name }}</h2>
<h2>学校地址:{{ address }}</h2>
</div>
</template>
<script>
// 局部引入混合
// import {hunhe} from '../mixin'
export default {
name: "School",
data() {
return {
name: "shangguigu",
address: "beijing",
};
},
// mixins:[hunhe]
};
</script>
<style></style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Student.vue
<template>
<div>
<h2 @click="showName">学生姓名:{{ name }}</h2>
<h2>学生性别:{{ sex }}</h2>
</div>
</template>
<script>
// 局部引入一个混合
// import {hunhe} from '../mixin'
export default {
name: "Student",
data() {
return {
name: "eryajf",
sex: "男",
};
},
// mixins:[hunhe]
};
</script>
<style></style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# main.js
import Vue from "vue";
import App from "./App.vue";
import { hunhe, hunhe2 } from "./mixin";
Vue.config.productionTip = false;
Vue.mixin(hunhe, hunhe2); // 全局注册
new Vue({
el: "#app",
components: { App },
render: (h) => h(App),
});
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# mixin.js
export const hunhe = {
methods: {
showName() {
alert(this.name);
},
},
mounted() {
console.log("hello");
},
};
export const hunhe2 = {
data() {
return {
x: 100,
y: 200,
};
},
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 笔记
- 功能:可以把多个组件共用的配置提取成一个混入对象
- 使用方式: 第一步定义混合:
{
data(){....},
methods:{....}
....
}
1
2
3
4
5
2
3
4
5
第二步使用混入:
全局混入:Vue.mixin(xxx)
局部混入:mixins: ['xxx']
上次更新: 2024/11/19, 23:11:42