个人技术分享

Vue---混入

Vue2—混入

mixin(混入):可以将组件中共用的配置提取到一个对象内,以此便不用再每个组件中都写一遍了

声明mixin

  • 定义mixin/index.js文件
const mixinData = {
    data(){
        return {name:'张三'}
    },
    methods:{
        handleHello(){
            return '你好'+this.name
        }
    }
}
export default mixinData
  • 此时mixinData中有name和handleAge函数

局部使用

<template>
  <div class="about">
    <h1>我是{{ name }}</h1>
    <h1>{{handleHello()}}</h1>
  </div>
</template>
<script>
// 导入自定义mixin
import mixinData from "@/mixin";
export default {
  name :'About',
  data(){
    // 取值
    return {name:mixinData.data().name}
  },
  methods:{
  },
	// 导入
  mixins:[mixinData]
}
</script>
  • mixinData.data().name:获取mixin中的name

image-20240430163946970

全局使用

// main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
// 导入
import mixinData from "@/mixin";

Vue.config.productionTip = false
// 创建实例
Vue.mixin(mixinData)
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

<template>
  <div class="about">
    <h1>我是{{ name }}</h1>
    <h1>{{handleHello()}}</h1>
  </div>
</template>
<script>

export default {
  name :'About',
}
</script>
/h1>
  </div>
</template>
<script>

export default {
  name :'About',
}
</script>