# 1.mixins 基本使用
# demoMixin
js | demoMixin.js |
| export const demoMixin = { |
| data() { |
| return { |
| message: "你好呀,李银河" |
| } |
| }, |
| methods: { |
| foo() { |
| console.log("demo mixin foo"); |
| } |
| }, |
| created() { |
| console.log("执行了demo mixin created"); |
| } |
| } |
# App
vue | // App |
| <template> |
| <div> |
| <h2>{{ message }}</h2> |
| <button @click="foo">按钮</button> |
| </div> |
| </template> |
| |
| <script> |
| import { demoMixin } from './demoMixin'; |
| |
| export default { |
| mixins: [demoMixin], |
| data() { |
| return { |
| title: "Hello World" |
| } |
| }, |
| methods: { |
| |
| } |
| } |
| </script> |
| |
| <style scoped></style> |
参考结果:
# 2.mixins 合并规则
vue | <template> |
| <div> |
| <h2>{{ message }}</h2> |
| <button @click="foo">按钮</button> |
| </div> |
| </template> |
| |
| <script> |
| import { demoMixin } from "./mixins/demoMixin"; |
| |
| export default { |
| data() { |
| return { |
| title: "Hello World", |
| message: "Hello App", |
| }; |
| }, |
| methods: { |
| foo() { |
| console.log("app foo"); |
| }, |
| }, |
| computed: {}, |
| watch: {}, |
| |
| created() { |
| console.log("App created 执行"); |
| }, |
| |
| mixins: [demoMixin], |
| }; |
| </script> |
| |
| <style scoped></style> |
参考结果:
# 3.mixins 全局混入
js | app.mixin({ |
| data() { |
| return {} |
| }, |
| methods: { |
| |
| }, |
| created() { |
| console.log("全局的created生命周期"); |
| } |
| }); |
# 4.extends (很少用到)
# BasePage
vue | <template> |
| <div> |
| <h2>我是BasePage</h2> |
| </div> |
| </template> |
| |
| <script> |
| export default { |
| data() { |
| return { |
| title: "我是BasePage", |
| }; |
| }, |
| methods: { |
| bar() { |
| console.log("我是BasePage"); |
| }, |
| }, |
| }; |
| </script> |
| |
| <style scoped></style> |
# 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> |
# App
vue | <template> |
| <div> |
| <home /> |
| </div> |
| </template> |
| |
| <script> |
| import Home from "./Home.vue"; |
| |
| export default { |
| components: { |
| Home, |
| }, |
| }; |
| </script> |
| |
| <style scoped></style> |
参考结果: