programing

Vue 인스턴스에서 글로벌 믹스인 메서드를 사용하는 방법

prostudy 2022. 7. 3. 09:03
반응형

Vue 인스턴스에서 글로벌 믹스인 메서드를 사용하는 방법

Global Mixin을 사용하여 Vue를 사용하여 글로벌 도우미 메서드를 작성하는 경우 다음과 같은 상황이 발생한다고 가정합니다.

import Vue from "vue";

Vue.mixin({
    methods: {
        replaceString: function (word) {
            return word.toLowerCase().replace(/\W/g, '');
        }
    }
});

let vm = new Vue({
    methods: {
        doSomething: function() {
             console.log(this.replaceString('Hello World'); //helloword
        }
    }
});

다른 메서드, 컴포넌트 및 그 자식 내부에서 메서드를 호출할 수 있다는 것을 알고 있습니다.그러나 Vue 인스턴스 "vm"에서 mixin 메서드 "replaceString"을 호출하려면 어떻게 해야 합니까?vm.replaceString을 사용하려고 했는데 계속 "정의되지 않음"이 반환됩니다.

코드에 약간의 변경을 가하면 됩니다.

  1. mixin(Vue.mixin 대신 var mixin)의 정의를 변경해야 합니다.
  2. 믹스인을 새 vue 구성 요소로 가져오기(subsins = [vubsin])

    import Vue from "vue";
    
    var mixin = {
        methods: {
            replaceString: function (word) {
                return word.toLowerCase().replace(/\W/g, '');
            }
        }
    };
    
    let vm = new Vue({
        mixins: [mixin]
        methods: {
            doSomething: function() {
                console.log(this.replaceString('Hello World'); //helloword
            }
        }
    });
    

이 청크 코드가 당신이 찾고 있는 것이라고 생각합니다.

var mixin = {
methods: {
foo: function () {
  console.log('foo')
},
   conflicting: function () {
      console.log('from mixin')
   }
 }
}

var vm = new Vue({
  mixins: [mixin],
methods: {
  bar: function () {
  console.log('bar')
  },
    conflicting: function () {
      console.log('from self')
    }
  }
})

vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"

문서에서

언급URL : https://stackoverflow.com/questions/54715799/how-can-i-use-a-global-mixin-method-from-a-vue-instance

반응형