今天無意在百度上搜了一下mixins,然後哐哐得出來的都是mixin的概念,mixins的原理(幾句話咱也沒看懂),有幾個是用法的,但是說的也是含含糊糊。。還有的畫思維導圖的。。挺簡單的問題非要複雜化。。。 其實我就想知道咋用,能幹什麼,其他的我真不關心。。(最好帶那種步驟的纔好~ haha…)
好了,步入正題,mixin官方文檔上得解釋是:
官方文檔介紹的。。有點官方。。。反正我第一遍是沒看懂。。
個人理解:mixin可以定義公用的,data,created,methods,computed,watch… 可以把mixin理解成,html引入js文件就可以調用js文件的方法,minxin還有一個強大之處就是(混入),相同的變量/方法名會合並在一起,如果有相同名字,當前文件的變量或者方法會覆蓋mixin文件的名字或者方法
下面是使用:
src目錄創建minxins文件,裏面創建index.js文件
然後頁面上這樣 相同顏色的要對應上,代碼在最後面我會粘上
頁面顯示:
然後註釋掉.vue文件的data值
頁面變成了
所以當相同名字頁面權重大於引入文件,代碼在下面,可以粘貼下來自己測試~~
<template>
<div>
<div>{{testMix}}</div>
<div @click="mixinsFun">{{testMix}}</div>
<input type="text" v-model="testMix">
<div>{{testMix2}}</div>
</div>
</template>
<script>
import {mixinstest} from '../mixins/index'
export default {
mixins: [mixinstest],
data (){
return {
// testMix:'這是組件的數據'
}
},
created(){
console.log('這是組件的created')
},
methods: {
mixinsFun(){
console.log('調用組件的methods的函數')
}
},
computed:{
testMix2(){
return this.testMix+':這是組件計算結果'
}
},
watch: {
testMix(newVal,oldVal){
console.log('組件的watch')
}
}
}
</script>
<style>
</style>
// 創建一個需要混入的對象
export const mixinstest = {
data(){
return {
testMix: '混入對象的data'
}
},
created(){
console.log('這是混入對象的created')
},
methods:{
mixinsFun(){
console.log('調用混入對象的methods的函數')
}
},
computed:{
testMix2(){
return this.testMix+':這是混入對象計算結果。'
}
},
watch: {
testMix(newVal,oldVal){
console.log('混入對象的watch')
}
}
}