詳解vue之mixin的使用
阿新 • • 發佈:2021-11-27
目錄
- 之mixin的使用
- mixin之中的data資料訪問
- mixin / index.
- Home.vue
- About2.vue
- mixin中的 methods方法和computed使用
- mixin / index.js
- Home.vue
- About2.vue
- 總結
vue之mixin的使用
- 作用:在引入元件之後,則是將元件內部的內容如data等方法、method等屬性與父元件相應內容進行合併。相當於在引入後,父元件的各種屬性方法都被擴充了
- data資料IWtGOJ的等訪問原則:若是使用mixin的當前元件有該 data資料 或者 methods方法的話 直接運用的是當前元件的資料或者方法,否則的話直接繼承mixin內部的資料與方法
- 注意點:可以定義共用的變數,在每個元件中使用,引入元件中之後,各個變數是相互獨立的,值的修改在元件中不會相互影響
- 注意點2:mixin是在引入元件之後與元件中的物件和方法進行合併,相當於擴充套件了父元件的data資料與方法等,可以理解為形成了一個新的元件
mixin之中的data資料訪問
mixin / index.js
export default { data () { return { msg: "我是mixin內的msg" } },created () { },mounted () { },methods: { } }
Home.vue
- 在Home元件中使用mixin
<template&http://www.cppcns.comgt; <div> <div>home -- {{ msg }}</div> /* home修改的msg */ </div> </template> <script> import mixin from "@/mixin/index.js"; export default { name: "Home",mixins: [mixin],data() { return { }; },created() { // 拿mixwww.cppcns.comin的data資料 console.log("home列印一下",this.msg); //home列印一下 我是mixin內的msg // 修改mixin的data資料 this.msg = "home修改的msg"; console.log("home列印一下",this.msg); // home列印一下 home修改的msg },methods: { },}; </script> <style lang="s" scoped> </style>
About2.vue
<template> <div> <div>about2 -- {{ msg }}</div> /* about2修改的msg */ </div> </template> <script> import mixin from "@/mixin/index.js"; export default { name: "About2",components: {},data() { return { msg: "本地的msg",}; },created() { console.log("about2列印一下",this.msg); // 本地的msg this.msg = "about2修改的msg"; console.log("about2列印一下",this.msg); // about2修改的msg // 最後頁面 顯示的 about2修改的msg 這個資料 },}; </script> <style lang="scss" scoped> </style>
mixin中的 methods方法和computed使用
mixin / index.js
export default {
data () {
return {
msg: "我是mixin內的msg"
}
},created () { },computed: {
UserName (http://www.cppcns.com) {
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> /* home --- msg-home修改的msg UserName-我是計算屬性的UserName */ </div> </template> <script> import mixin from "@/mixin/index.js"; export default { name: "Home",data() { return {}; },created() { // 拿mixin的data資料 console.log("home列印一下",this.msg); // home列印一下 home修改的msg // 呼叫mixin中的 tipMsg 方法 this.tipMsg(); // minxin內的tipMsg方法 home修改的msg this.tipInfo("我是home的菜雞info"); // minxin內的tipInfo方法 我是home的菜雞info },methods: {},}; </script> <style lang="scss" scoped> </style>
About2.vue
<template> <div> <div>about2 -- {{ msg }} UserName-{{ UserName }}</div> /* about2 -- about2修改的msg UserName-我是計算屬性的UserName */ </div> </template> <script> import mixin from "@/mixin/index.js"; export default { name: "About2",this.msg); // about2修改的msg // 最後頁面 顯示的 about2修改的msg 這個資料 this.tipMsg(); // 最後列印 -> 我是about2本地的tipMsg方法 this.tipInfo(); // minxin內的tipInfo方法 undefined },methods: { tipMsg() { console.log("我是about2本地的tipMsg方法"); },}; </script>
總結
本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注我們的更多內容!