saipavan
saipavan

Reputation: 81

Accessing Vue Component scope from external javascript

Can I access Vue components data properties and methods from external javascript? I am trying to create a hybrid application where a portion of the screen is a Vue component, and I want to call a method inside that component on click of a button which is handled by pure js. Is there a way to achieve this?

Thanks!

Upvotes: 6

Views: 10150

Answers (2)

thibautg
thibautg

Reputation: 2052

Yes. You need to assign your Vue object to a variable (i.e. vue) and then you can access vue.methodName() and 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/[email protected]/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>

Upvotes: 12

LShapz
LShapz

Reputation: 1756

Yes, you can add an event listener to the Vue component that listens for the button click's event. See example here on codepen.

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>

Upvotes: 0

Related Questions