I have a very basic Vue.js app that looks like this:
index.html (just the <body> for succinctness)
<div id="root"></div>
main.js
var config = {
title: 'My App',
}
new Vue({
el: '#root',
template: '<div>{{ config.title }}</div>',
})
This gives me:
Property or method "config" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
(found in root instance)
I'm guessing it's because Vue is looking for it in the data store rather than window. Is there some way to signal that config is a global here, or a better way to do this entirely? I suppose I could pass the config object as a prop to my root Vue instance, but it seems like only components accept props. Thanks for any insights on this.
You can try to define your app as follows:
new Vue({
el: '#root',
template: '<div>{{ config.title }}</div>',
data: function() {
return {
config: window.config
}
}
})
In the above definition, your this.config within the root component points to window.config - the global variable.
If you are just trying to pass the App Name in as a hard-coded string you can do something like this:
var nameMyApp = new Vue({
el: '#root',
data: { input: 'My App' },
computed: {
whosapp: function () {
return this.input
}
}
})
With your html like this:
<div id="root">
<div v-html="whosapp"></div>
</div>
Which will pass the value of input to the whosapp div.
But, if you're looking for something more dynamic, this would be the way to go:
With the same html as above...
var nameMyApp = new Vue({
el: '#root',
data: { input: 'My App' },
The initial value is set to My App, which is what will display if not changed through a function call on the method.
methods: {
update: function(name) {
this.input = name;
}
},
Here is where we define a method that, when called, passes in the parameter to update this.input.
computed: {
whosapp: function () {
return this.input
}
}
})
nameMyApp.update("New Name");
And here is where we call the function, giving it the new parameter; making sure that the parameter is a string.
I hope this is what you're looking for.
Related
I want to change a data property and run a method on my Vue instance within Laravel. However due to using webpack and laravel I can't seem to access the instance how I would expect to:
So window.app doesn't appear to be the correct instance of my Vue class.
Below is the Blade View i'm loading, as you can see I append a script tag to my main layout.blade.php, simply trying to change the Vue instance data property, and run a method.
#push('scripts')
<script>
app.unsaved = true;
app.triggerEvent(null, 'models', null);
</script>
#endpush
Below is part of my app.js (resources/assets/js/app.js):
const app = new Vue({
el: '#app',
components: {
'models-select': ModelsSelect
},
data: {
showModel: false,
unsaved: false
},
mounted: function() {
let _self = this;
(function() {
document.querySelectorAll("input, textarea, select").forEach(function(e) {
e.addEventListener('change', function() {
_self.unsaved = true;
e.classList.add('is-changed');
});
});
function unloadPage(){
if (_self.unsaved) return 'You appear to have un-saved changes!';
}
window.onbeforeunload = unloadPage;
})();
},
methods: {
triggerEvent: function(event, target, property)
{
app.$refs[target].update(event, property);
}
As you can see i'd expect to manipulate the Vue instance through the global app variable I have defined within the app.js. However this doesn't appear to be the case.
I get the following error when running the triggerEvent method:
app.triggerEvent is not a function
In your app.js file, change const app = new Vue({ to window.app = new Vue({.
Then within your <script> tags, change it to this.
<script>
window.app.unsaved = true;
window.app.triggerEvent(null, 'models', null);
</script>
I'm trying to emit something from within my VueJS component to a function which sits in the html page containing the component. Am I missing something, or is this not possible?
Within my component as a method:
insert: function(){
this.$emit('insertItem', 123);
}
In the page containing the component:
<medialibrary #insertItem="insertItem(arg);"></medialibrary>
<script>
function insertItem(arg){
console.log('insertItem');
console.log(arg);
}
</script>
This is actually more possible than it seems at first look. If the function is global (in particular, visible to the parent Vue), it can be called by the Vue even if it is not a method of the Vue. (It would arguably be a better idea to create a method that calls the global function.)
The main difficulty with your code was camelCasing where it should be kebab-case.
If you want insertItem to get the arg from the $emit, the HTML should only give the function name, and Vue will take care of passing the args:
<medialibrary id="app" #insert-item="insertItem"></medialibrary>
My snippet uses your original code, which provides arg from the parent Vue.
function insertItem(arg) {
console.log('insertItem');
console.log(arg);
}
new Vue({
el: '#app',
data: {
arg: 'hi there'
},
components: {
medialibrary: {
template: '<div><button #click="insert">Insert</button></div>',
methods: {
insert() {
console.log("Emit");
this.$emit('insert-item', 123);
}
}
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.2/vue.min.js"></script>
<medialibrary id="app" #insert-item="insertItem(arg);"></medialibrary>
This is a pseudocode to illustrate my question. When the script is run, it will encounter the error func1 is not defined. How can I go about this?
app.js
require ('./helper');
new Vue ({
el: "#app",
created: function () {
func1()
}
});
helper.js
module.exports = function () {
$.notify('Hi', {
position: "bottom right",
className: "success"
});
};
Thanks in advance!
You might have to save the imported function to a variable in your app.js file. It depends on what bundler you use (e.g. browserify or webpack or else). Functions declared outside of the parameter object you are passing to Vue should be accessible:
// app.js
var func1 = require('./helper');
new Vue ({
el: "#app",
created: function () {
func1();
}
});
In your helpers.js, you need a reference to jQuery. You can either include the library (jQuery and $ will be available globally on the window object) or like in the example below, install it from https://www.npmjs.com/package/jquery and bundle it with your own code.
// helper.js
var $ = require('jquery');
module.exports = function () {
$.notify('Hi', {
position: "bottom right",
className: "success"
});
};
If you want to call this function in more than one component's created method, you can create a mixin, which then will be passed to specific component.
//YourMixin.js
new Vue({
created: function () { ... }
})
//Component
let mixin = require('YourMixin')
new Vue({
mixins: [mixin],
...
})
I'm trying to build a simple app in vue and I'm getting an error. My onScroll function behaves as expected, but my sayHello function returns an error when I click my button component
Property or method "sayHello" is not defined on the instance but
referenced during render. Make sure to declare reactive data
properties in the data option. (found in component )
Vue.component('test-item', {
template: '<div><button v-on:click="sayHello()">Hello</button></div>'
});
var app = new Vue({
el: '#app',
data: {
header: {
brightness: 100
}
},
methods: {
sayHello: function() {
console.log('Hello');
},
onScroll: function () {
this.header.brightness = (100 - this.$el.scrollTop / 8);
}
}
});
I feel like the answer is really obvious but I've tried searching and haven't come up with anything. Any help would be appreciated.
Thanks.
But for a few specific circumstances (mainly props) each component is completely isolated from each other. Separate data, variables, functions, etc. This includes their methods.
Thus, test-item has no sayHello method.
You can get rid of the warning by using .mount('#app') after the Vue instance rather than the el attribute.
Check the snippet below;
var app = new Vue({
data: {
header: {
brightness: 100
}
},
methods: {
sayHello: function() {
console.log('Hello');
},
onScroll: function () {
this.header.brightness = (100 - this.$el.scrollTop / 8);
}
}
}).mount('#app');
Please note; the following might not be necessary but did it along the way trying to solve the same issue: Laravel Elixir Vue 2 project.
I am trying to call a parent/root level method on a child component in Vue.js, but I keep getting a message saying TypeError: this.addStatusClass is not a function.
Vue.component('spmodal', {
props: ['addStatusClass'],
created: function() {
this.getEnvironments();
},
methods: {
getEnvironments: function() {
this.addStatusClass('test');
}
}
});
new Vue({
el: '#app',
methods: {
addStatusClass(data) {
console.log(data);
}
}
});
Here is a full JSBIN example: http://jsbin.com/tomorozonu/edit?js,console,output
If I call this.$parent.addStatusClass('test'); it works fine, but based on the Vue.js documentation, this is bad practice and I should be using props which is not working.
specifying the prop does nothing on its own, you have to actually pass something to it from the parent - in this case, the function.
<spmodal :add-status-class="addStatusClass"></spmodal>