102.vue3中全局mixins的使用 1.mixin.js文件定義 2.全局文件main.js引入mixin 3.組件內使用mixin

1.mixin.js文件定義

mixin.js文件定義

// mixin.js

export default {
    data () {
      return {
        from: 'from mixin data'
      }
    },
    mounted () {
      console.log('from mixin mounted')
    },
    methods: {
      handleInit () {
        console.log('from mixin methods')
      }
    }
  }

2.全局文件main.js引入mixin

全局文件main.js引入mixin

// main.js

import { createApp } from 'vue'
import App from './App.vue'
import mixin from './mixin/index.js'

const app = createApp(App)

app.mixin(mixin)

app.mount('#app');

3.組件內使用mixin

1.模板內直接使用mixin

// 1.模板內直接使用mixin

<template>
  <div>
    <h3>mixin</h3>
    <el-button @click="handleInit">mixin使用</el-button>
  </div>
</template>

2.組件方法調用mixin

// 組件方法調用mixin

<template>
  <div>
    <h3>mixin</h3>
    <el-button @click="onClick">組件內方法調用mixin使用</el-button>
  </div>
</template>

<script>
// getCurrentInstance獲取當前組件實例
import { getCurrentInstance, onMounted } from "vue";

export default {
  setup () {
    const { proxy, ctx } = getCurrentInstance()
   
    onMounted(() => {
      console.log("組件內mounted");
    })

    const onClick = () => {
      console.log('組件內方法調用mixin使用')
      proxy.handleInit()
    }

    return {
      onClick
    }
  }
}
</script>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章