vue之mixin的使用
- 作用:在引入组件之后,则是将组件内部的内容如data等方法、method等属性与父组件相应内容进行合并。相当于在引入后,父组件的各种属性方法都被扩充了
- data数据的等访问原则:若是使用mixin的当前组件有该 data数据 或者 methods方法的话 直接运用的是当前组件的数据或者方法,否则的话直接继承mixin内部的数据与方法
- 注意点:可以定义共用的变量,在每个组件中使用,引入组件中之后,各个变量是相互独立的,值的修改在组件中不会相互影响
- 注意点2:mixin是在引入组件之后与组件中的对象和方法进行合并,相当于扩展了父组件的data数据与方法等,可以理解为形成了一个新的组件
mixin之中的data数据访问
mixin / index.js
export default {
data () {
return {
msg: "我是mixin内的msg"
}
},
created () {
},
mounted () { },
methods: {
}
}
Home.vue
<template>
<div>
<div>home -- {{ msg }}</div>
</div>
</template>
<script>
import mixin from "@/mixin/index.js";
export default {
name: "Home",
mixins: [mixin],
data() {
return { };
},
created() {
console.log("home打印一下", this.msg);
this.msg = "home修改的msg";
console.log("home打印一下", this.msg);
},
methods: {
},
};
</script>
<style lang="scss" scoped>
</style>
About2.vue
<template>
<div>
<div>about2 -- {{ msg }}</div>
</div>
</template>
<script>
import mixin from "@/mixin/index.js";
export default {
name: "About2",
mixins: [mixin],
components: {},
data() {
return {
msg: "本地的msg",
};
},
created() {
console.log("about2打印一下", this.msg);
this.msg = "about2修改的msg";
console.log("about2打印一下", this.msg);
},
methods: {
},
};
</script>
<style lang="scss" scoped>
</style>
mixin中的 methods方法和computed使用
mixin / index.js
export default {
data () {
return {
msg: "我是mixin内的msg"
}
},
created () { },
mounted () { },
computed: {
UserName () {
return "我是计算属性的UserName";
},
},
methods: {
tipMsg () {
console.log("minxin内的tipMsg方法", this.msg);
},
tipInfo (info) {
console.log("minxin内的tipInfo方法", info);
}
}
}
Home.vue
<template>
<div>
<div>home --- msg-{{ msg }} UserName-{{ UserName }}</div>
</div>
</template>
<script>
import mixin from "@/mixin/index.js";
export default {
name: "Home",
mixins: [mixin],
components: {},
data() {
return {};
},
created() {
console.log("home打印一下", this.msg);
this.msg = "home修改的msg";
console.log("home打印一下", this.msg);
this.tipMsg();
this.tipInfo("我是home的菜鸡info");
},
methods: {},
};
</script>
<style lang="scss" scoped>
</style>
About2.vue
<template>
<div>
<div>about2 -- {{ msg }} UserName-{{ UserName }}</div>
</div>
</template>
<script>
import mixin from "@/mixin/index.js";
export default {
name: "About2",
mixins: [mixin],
components: {},
data() {
return {
msg: "本地的msg",
};
},
created() {
console.log("about2打印一下", this.msg);
this.msg = "about2修改的msg";
console.log("about2打印一下", this.msg);
this.tipMsg();
this.tipInfo();
},
methods: {
tipMsg() {
console.log("我是about2本地的tipMsg方法");
},
},
};
</script>
mixin之 component的使用
链接: link.
|