认识Mixin
Mixin的基本使用
Mixin的合并规则
全局混入Mixin
extends
import { createApp } from 'vue';
import App from './01_mixin和extends/App.vue';
// import App from './02_compositionAPI基础/App.vue';
const app = createApp(App);
// 全局混入Mixin
app.mixin({
data() {
return {}
},
created() {
console.log("全局的created生命周期");
}
});
app.mount("#app");
App.vue
<template>
<div>
<home />
</div>
</template>
<script>
import Home from "./pages/Home.vue";
export default {
components: {
Home,
},
};
</script>
<style scoped></style>
01_mixin基本使用.vue
<template>
<div>
<h2>{{ message }}</h2>
<button @click="foo">按钮</button>
</div>
</template>
<script>
import { demoMixin } from "./mixins/demoMixin";
export default {
mixins: [demoMixin],
data() {
return {
title: "Hello World",
};
},
methods: {},
};
</script>
<style scoped></style>
02_mixin合并规则.vue
<template>
<div>
<h2>{{ message }}</h2>
<button @click="foo">foo</button>
</div>
</template>
<script>
import { demoMixin } from "./mixins/demoMixin";
export default {
mixins: [demoMixin],
data() {
return {
title: "Hello World",
message: "Hello App",
};
},
methods: {
foo() {
console.log("app foo");
},
},
computed: {},
watch: {},
created() {
console.log("App created 执行");
},
};
</script>
<style scoped></style>
demoMixin.js
export const demoMixin = {
data() {
return {
message: "Hello DemoMixin"
}
},
methods: {
foo() {
console.log("demo mixin foo");
}
},
created() {
console.log("执行了demo mixin created");
}
}
Home.vue
<template>
<div>
Home Page
<h2>{{ title }}</h2>
<button @click="bar">按钮</button>
</div>
</template>
<script>
import BasePage from "./BasePage.vue";
export default {
extends: [BasePage],
data() {
return {
content: "Hello Home",
};
},
};
</script>
<style scoped></style>
BasePage.vue
<template>
<div>
<h2>哈哈哈哈啊</h2>
</div>
</template>
<script>
export default {
data() {
return {
title: "Hello Page",
};
},
methods: {
bar() {
console.log("base page bar");
},
},
};
</script>
<style scoped></style>