programing

외부 javascript에서 Vue Component 범위 액세스

itsource 2022. 7. 21. 20:18
반응형

외부 javascript에서 Vue Component 범위 액세스

외부 Javascript에서 Vue 컴포넌트 데이터 속성 및 메서드에 액세스할 수 있습니까?화면의 일부가 Vue 컴포넌트인 하이브리드 어플리케이션을 만들려고 하는데, 순수 js로 처리되는 버튼을 클릭해서 그 컴포넌트 내의 메서드를 호출하고 싶습니다.이것을 달성할 수 있는 방법이 있나요?

감사합니다!

예. Vue 개체를 변수에 할당해야 합니다(예:vue)에 액세스 할 수 있습니다.vue.methodName()그리고.vue.propertyName:

// add you new Vue object to a variable
const vue = new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Play around in JSFiddle", done: true },
      { text: "Build something awesome", done: true }
    ]
  },
  methods: {
  	toggle: function(todo){
    	todo.done = !todo.done
    }
  }
});

// Add event listener to outside button
const button = document.getElementById('outsideButton');
button.addEventListener('click', function() {
	vue.toggle(vue.todos[1]);
});
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}
<script src="https://unpkg.com/vue@2.5.16/dist/vue.min.js"></script>
<div id="app">
  <h2>Todos:</h2>
  <ol>
    <li v-for="todo in todos">
      <label>
        <input type="checkbox"
          v-on:change="toggle(todo)"
          v-bind:checked="todo.done">

        <del v-if="todo.done">
          {{ todo.text }}
        </del>
        <span v-else>
          {{ todo.text }}
        </span>
      </label>
    </li>
  </ol>
</div>
<div class="outside">
  <button id="outsideButton">
    Click outside button
  </button>
</div>

예, 버튼 클릭 이벤트를 수신하는 Vue 구성 요소에 이벤트 수신기를 추가할 수 있습니다.코드펜의 예를 참조해 주세요.

JS

new Vue({
  el: '#app',
    methods: {
        clickMethod(event){
            if (event.target.id === 'outsideButton') {
                alert('button clicked')
            }
        }
    },
    created(){
        let localThis = this 
        document.addEventListener('click', this.clickMethod)
    }
})

HTML

<div>
    <button id="outsideButton">Button</button>
    <div id="app">
    </div>
</div>

언급URL : https://stackoverflow.com/questions/50611939/accessing-vue-component-scope-from-external-javascript

반응형