Vue uses mixins to define common methods (equivalent to using this in vue in js)

Vue uses mixins to define common methods (equivalent to using this in vue in js)

Specific steps:

  1. Create an imported file (eg: myMixin.js)

  2. myMixin.js write content

    export default {
          
          
    	methods: {
          
          
    	   // 通用的方法名称
    	   globalMethod() {
          
          
    	      console.log(this.msg); // 访问Vue实例的属性
    	   },
    	},
    };
    
  3. Call the page to introduce myMixin.js (omit the vue structure)

    import myMixin from "@/myMixin.js";
    export default {
          
          
      mixins: [myMixin],
      ...
    };
    
  4. Call method:

    1. call directly on the page
    <button @click="globalMethod"></button>
    
    1. Second call in the method (omit the vue structure)
     <button @click="handleClick">Click me</button>
     import myMixin from "@/myMixin.js";
     export default {
          
          
       mixins: [myMixin],
       data() {
          
          
         return {
          
          
           msg: "Hello World!",
         };
       },
       methods: {
          
          
         handleClick() {
          
          
          this.globalMethod(); // 在Vue组件中调用mixin中定义的全局方
        },
      },
    };
    

Guess you like

Origin blog.csdn.net/weixin_42947972/article/details/130538282