架子app
<div id="app"> {{msg}} </div> <script> let app = new Vue({ el:'#app', data:{ msg:'晓强' }, }) </script>
mixin偷懒ide
<div id="app"> {{msg}} // 我在这就是想看 msg 的内容 因此 须要 mixin 就能够啦 </div> <script> const myMixin={ data(){ return{ msg:'myMixin偷懒' } } }; let app = new Vue({ el:'#app', data:{ title:'晓强' }, mixins : [myMixin] }) </script>
咱们不只能够偷懒数据 也能够偷懒方法this
<div id="app"> {{msg}} </div> <script> const myMixin={ data(){ return{ msg:'myMixin偷懒' } }, created(){ this.SayHello(); }, methods:{ SayHello(){ console.log('hello') } } }; let app = new Vue({ el:'#app', data:{ title:'晓强' // 若是这个是 msg 就显示的是晓强 }, mixins : [myMixin] }) </script>
二mixin混入技术应用
最早开始的架子spa
<div id="app"> {{msg}} </div> <script> // 模态框 const Modal={ template:`<div v-if="isShow"><h3>模态框组件</h3></div>`, data(){ return{ isShow:false } }, methods:{ toggleShow(){ this.isShow = !this.isShow } } }; // 提示框 const Tooltip={ template:`<div v-if="isShow"><h2>提示框组件</h2></div>`, data(){ return{ isShow:false } }, methods:{ toggleShow(){ this.isShow = !this.isShow } } }; let app=new Vue({ el:'#app', data:{ msg:'mixin' } }) </script>
咱们能够发现 上面 的模态框 和提示框 有重复的代码component
提取ip
const toggleShow = { data() { return { isShow: false } }, methods: { toggleShow() { this.isShow = !this.isShow } } };
总体代码it
<body> <!--一个是模态框 一个是提示框 被弹出--> <!--他们两个看起来不同 用法不同 可是逻辑是同样的(切换boolean)--> <div id="app"> {{msg}} </div> <script> /* * 全局的mixin要格外当心 由于每一个组件实例建立时都会被调用 * Vue.mixin({ * data(){ * * } * }) * */ const toggleShow = { data() { return { isShow: false } }, methods: { toggleShow() { this.isShow = !this.isShow } } }; // 模态框 const Modal = { template: `<div v-if="isShow"><h3>模态框组件</h3></div>`, mixins: [toggleShow] }; // 提示框 const Tooltip = { template: `<div v-if="isShow"><h2>提示框组件</h2></div>`, mixins: [toggleShow] }; let app = new Vue({ el: '#app', data: { msg: 'mixin' }, components: { Modal, Tooltip }, template: ` <div> <Modal ref="motai"></Modal> <Tooltip ref="tooltip"></Tooltip> <button @click="handleModel">模态框</button> <button @click="handleTooltip">提示框</button> </div> `, methods: { handleModel() { this.$refs.motai.toggleShow() }, handleTooltip() { this.$refs.tooltip.toggleShow() } }, }) </script>