How can I call the test vue in javascript? Here is my code, I want to call test when I do something in javascript function.
function clickit() {
this.test.fetchTestData();
}
var test = new Vue({
el: '#viewport',
data: {
test_data: []
},
mounted: function () {
this.fetchTestData();
},
methods: {
fetchTestData: function () {
$.get(test.json, function (data) {
this.test_data = data;
alert(this.test_data.isActive);
});
}
}
});
You are attempting to use this inside clickit() where this refers to window, so you just need to remove this and it should call the method inside the view model:
function clickit() {
test.fetchTestData();
}
If you compile this code with 'vue-cli-service build' the variable 'test' will not be defined, but you can make it visible to javascript in the mounted function:
new Vue({
el: '#viewport',
data: {
test_data: []
},
mounted: function () {
window.test=this;
},
methods: {
fetchTestData: function () {
$.get(test.json, function (data) {
this.test_data = data;
alert(this.test_data.isActive);
});
}
}
});
Then you can call it from javascript:
function clickit() {
window.test.fetchTestData();
}
Another way to call VueJs method using external java-script.
Firstly we should create a file. name event.js
import Vue from 'vue';
export default new Vue({
data: {
}
});
After that we should import that event.js to our component
import Event from "../event.js";
Then we can emit an event on our javascript function like below
function yourJavascriptFunction(){
Event.$emit("fetchdata");
}
In your component, mounted property should be like below:
mounted() {
Event.$on("fetchdata", group => {
this.fetchData();
});
},
methods() {
async fetchData() {
console.log('hoooray :)');
}
},
Related
I have attached a click event handler to my ChartJS-derived component, like this:
export default {
extends: HorizontalBar,
data() {
return {
my_data: [],
options: {
onClick: function(event, args) {
//need to access my_data here
}
},
};
},
}
I need to access one of my data members inside the handler. Unfortunately, this.my_data doesn't work here. ChartJS documentation tells me that this event is called in the context of the Chart component, not my Vue component. How can I get access to my_data?
update
So I'm now using #Dan's way of defining the handler:
export default {
extends: HorizontalBar,
data() {
return {
my_data: [],
options: {
onClick: this.ClickHandler,
},
};
},
methods: {
ClickHandler: function(event, args) {
var datapoint = this.getElementAtEvent(event);
var value = this.my_data[datapoint._datasetIndex];
},
}
}
The handler is called correctly, but this is now refering to my Vue component and therefore I do not have any reference to the Chart context to call its getElementAtEvent.
So if I declare it in front of onClick above, I get the Chart context in this, but no longer have access to my_data. If I use your way, I get this.my_data, but lose Chart context.
You need to put the handler into your methods object and then reference it from the chart options handler:
data() {
return {
my_data: [],
options: {
onClick: this.ClickHandler,
}
};
},
methods: {
ClickHandler: function(event, points) {
// Here is how to access the chart
const c = this._data._chart;
const datapoint = c.getElementAtEvent(event)[0];
const indexBar = datapoint._index;
const indexSegment = datapoint._datasetIndex;
// Do whatever with this.my_data, indexBar, and indexSegment
}
}
The chart is accessible to the component through this._data._chart.
Create a closure variable
data() {
const vm = this;
return {
my_data: [],
options: {
onClick: function(event, args) {
this.chartjs.something;
vm.my_data[]
}
}
}
I'm using vue in laravel and trying to get a controller function that I'm hitting to return the data so that I can use it in the data() section of my vue template.
I know the controller function returns what I need, but I'm not so sure how I need to handle the return/response in the axios call in order to start placing the data into the data() function in vue
Blade/Vue template
import moment from 'moment'
export default {
name: 'calendar',
data () {
return {
events: [
{
title: 'test',
allDay: true,
start: '2019-08-17',
},
],
config: {
defaultView: 'month',
eventRender: function(event, element) {
console.log(event)
}
},
}
},
created() {
this.fetchTasks();
},
methods: {
fetchTasks() {
axios.get('/landing/tasks' )
.then((response) => {
// handle success
this.assetOptions = response.data;
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
});
}
}
}
Route
Route::get('/landing/tasks', 'landingController#getTasks')
->name('landing/tasks');
Controller
public function getTasks()
{
$getTask = Task::getTaskForLanding();
$result = array();
foreach($getTask as $id => $task){
$result[$task->taskt_id][] = $task;
}
}
If you are certain that the Controller returns what you need, the only thing you are missing is declaration of assetOptions. To be able to assign response.data to assetOptions later on, you have to declare it in the data function first.
data() {
return {
...
assetOptions = []; // assuming you are expecting an array
...
};
}
Once that is done, you are all set.
Let's suppose that I have the following situation, using a Global Mixin to create a global helper method with 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
}
}
});
I know that I can invoke the method inside the other methods, inside of the component and their childs. But how can I invoke the mixin method "replaceString" from the Vue instance "vm"?
I tried to use "vm.replaceString", but keeps returning "undefined".
Few changes to your code and it works:
You should change the definition of your mixin (var mixin instead of Vue.mixin)
Import the mixin to your new vue component (mixins = [mixin])
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
}
}
});
I think this chunk o code is what you are looking for:
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"
From the docs
I want to display the updated data in the modal. There is a click function which trigger the testing(data) function below.
The data comes out right in the function. However, the template doesn't seem to update, it still displays the previous data. How can I fix this?
Script:
function testing(data) {
const testingLink = new Vue ({
el: '#test',
data: { selected: data },
methods: {
showDialog: function() { $("#test).modal() }
}
})
testingLink.showDialog()
}
You shouldn't create a Vue Instance in a repeatable function
Try it in following way:
const testingLink = new Vue ({
el: '#test',
data: { selected: null },
methods: {
showDialog: function(data) {
this.selected = data
$("#test").modal()
}
}
})
testingLink.showDialog(YOUR_DATA_YOU_WANT_TO_PASS)
I have two Vue.js components Lobby and Game. I want to use Game as a model that contains all logic to create a game and trigger it via the Lobby component.
if I run the app and click on the button I get the following error
Uncaught TypeError: game.createGame is not a function
at click (eval at createFunction (vue.js:9923), <anonymous>:2:76)
at HTMLButtonElement.invoker (vue.js:1827)
How can I access the game method from the Lobby component? Thanks!
let Game = {
methods: {
createGame: function () {
console.log('createGame clicked')
}
}
}
let Lobby = {
template: `
<div>
<button v-on:click="game.createGame()">Create</button>
</div>
`,
data() {
return {
'game': Game
}
},
}
If you want to call a method from another component you can use Event bus from Vue.js
The main idea is that you have to emit a global call in A component and receive it in B component using bus.$on
var bus = new Vue();
Vue.component('Increment', {
template: "#inc",
data: function() {
return ({count: 0})
},
methods: {
increment: function(){
var increment = ++this.count
bus.$emit('inc', increment)
}
}
})
Vue.component('Display', {
template: "#display",
data: function(){
return {count: 0}
},
created: function(){
bus.$on('inc', function(num){
this.count = num
}.bind(this));
}
})
vm = new Vue({
el: "#example",
})
https://jsfiddle.net/emwcoy36/