Mix in Mixins

Mixins: are a
very flexible way of distributing reusable functionality in Vue components. Mixins can contain arbitrary component options. When a component uses a mixin, all the options of the mixin will be mixed into the options of the component itself.

define mixins

It is also very simple to define mixin, it is just an object, but this object can contain some common configurations in Vue components, such as data, methods, created, etc.

define a mixin object

export const mixins = {
    
    
    data(){
    
    
        return {
    
    
            msg:'我是myMixins中的msg',
            list:[
                {
    
    id:1,value:1},
                {
    
    id:2,value:2},
                {
    
    id:3,value:3},
                {
    
    id:4,value:4},
            ]
        }
    },
    methods:{
    
    
        //
        click(){
    
    
            // console.log('我是混入中的click方法')
            document.write('我是混入中的click方法')
        }
    },
    created() {
    
    
        console.log('我是混入的组件')
    }
}

Partial mix-in

Mix the mixed-in object into the current component, which is the same as the component reference method

<template>
<div>
  <div>
    <p>{
    
    {
    
    msg}}</p>
    <ul>
      <li v-for="(item,index) in list" :key="index">
        <p>混入组件中数组对象的id:{
    
    {
    
    item.id}}</p>
        <p>混入组件中数组对象的value:{
    
    {
    
    item.value}}</p>
      </li>
    </ul>
    <span>点击之后执行混入组件中的方法:</span>
    <button @click="click">按钮</button>
  </div>
</div>
</template>

<script>
// 导入混入的组件
import {
    
    mixins} from "../mixins/myMixins";

export default {
    
    
  name: "fatherView",
  // mixins: [mixins],
  created(){
    
    
    console.log("组件调用minxi数据",this.msg);
  },
  methods:{
    
    

  }
}
</script>

<style scoped>

</style>

global mixins

Global mixin means that mixin can be used in any component of the project

在main.js中添加

import {
    
    mixins} from "@/mixins/myMixins.js";
app.mixin(mixins)

全局引入混入后将mixins的引入注释掉一样可以用

<template>
<div>
  <div>
    <p>{
    
    {
    
    msg}}</p>
    <ul>
      <li v-for="(item,index) in list" :key="index">
        <p>混入组件中数组对象的id:{
    
    {
    
    item.id}}</p>
        <p>混入组件中数组对象的value:{
    
    {
    
    item.value}}</p>
      </li>
    </ul>
    <span>点击之后执行混入组件中的方法:</span>
    <button @click="click">按钮</button>
  </div>
</div>
</template>

<script>
// 导入混入的组件
// import {mixins} from "../mixins/myMixins";

export default {
    
    
  name: "fatherView",
  // mixins: [mixins],
  created(){
    
    
    console.log("组件调用minxi数据",this.msg);
  },
  methods:{
    
    

  }
}
</script>

<style scoped>

</style>

效果图:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_50370865/article/details/128401541