This must be simple, but haven't cracked it...
In vue, I think I get how to pass props from parent to child components. And I understand that I have an app state in the data member of the vue instance. What I don't understand is how to get the data state into the root app as props.
It seems there are a few ways to organize a vue app, so here's what I'm trying to make work:
index.ts
import app from './app.vue'
export default new Vue({
// App Root Element
el: '#app',
render: (c) => c('app'),
components: {
app
},
data: {
someValue: 42
}
})
app.vue
<template>
<div>
Some Value: {{someValue}}
</div>
</template>
<script lang="ts">
export default {
props: ['someValue']
};
</script>
I assume it should be something like the following, but I don't know how to get a reference directly to the data - unless I keep a reference to it outside of vue for this purpose, but that seems like it should not be necessary:
render: (c) => c('app', { someValue: ??? }),
Use this to get data or property values inside your render method (or methods or computed values, etc). Don't use an arrow function to define your render function if you're going to use this inside it.
new Vue({
el: "#app",
render(c) {
return c('app', {props:{someValue: this.someValue}})
},
components: {
app
},
data: {
someValue: 42
}
})
Example.
console.clear()
const app = {
props: ["someValue"],
template: `<div>Some Value: {{someValue}}</div>`
}
new Vue({
el: "#app",
render(c) {
return c('app', {props:{someValue: this.someValue}})
},
components: {
app
},
data: {
someValue: 42
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
</div>
As #RoyJ pointed out, this is the key section of the documentation.
Related
I'd like to get access to vm data from outside the instance like so:
myComponent.vue
export default {
data() {
return {
name: 'Joe'
};
}
}
main.js
var vm = new Vue({
el: '#app',
render: h => h(myComponent)
});
Desired Result
console.log(vm.name); // should return - Joe
For some reason, console returns undefined. What I'm doing wrong?
To access vue.js object datas from inside you can use $property_name. Example
var vm = new Vue({
el: '#app',
data() {
return {
name: "Kapucni",
}
},
template: '<div>{{ name }}</div>'
});
// use $name .property
console.log(vm.$data.name);
console.log(vm.$el);
// calling functions from $method, etc ...
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.10/dist/vue.js"></script>
<div id='app'>
</div>
Thanks to comments from ittus, I realised that I have to look for child components, not the root component.
We can get to child component like so:
vm.$children[0].name
where $children[0] is a direct (and first in this case) child of the root component.
I have this vue js component:
<template>
<div>
hello world
</div>
</template>
<script>
export default {
name: 'mycomp',
data: function () {
console.error("window.google_recaptcha_public_key", window.google_recaptcha_public_key);
return {
}
},
mounted() {
let app = this;
console.error("window.google_recaptcha_public_key2", window.google_recaptcha_public_key);
},
}
</script>
<style scoped lang="scss">
</style>
returns:
window.google_recaptcha_public_key undefined
window.google_recaptcha_public_key2 undefined
where can I leave painless and happy all global configuration?
notice this configuration lives in my laravel backend. So I wont copy paste all values from the backend to the front end
U can use Vue.prototype in main.js file, or in file you import Vue
Vue.prototype.Hereanyname = window.hereanyname;
and in your Vue application, you can use it
Hereanyname.thefunction
Real example on Laravel
in main.js
import Vue from 'vue';
Vue.prototype.Routes = window.routes;
new Vue({
el: '#app',
template: '<App/>',
components: {App}
});
in your application
:href="Routes.route('laravel.route.here')"
So for your case
import Vue from 'vue';
Vue.prototype.GoogleRecaptcha = window.google_recaptcha_public_key;
new Vue({
el: '#app',
template: '<App/>',
components: {App}
});
inside application
mounted() {
console.log(this.GoogleRecaptcha)
}
In Vue3, you no longer have the global Vue instance, so you need to assign the window as a global property on your app...
// main.js
app.config.globalProperties.window = window
Then in your components, window will just work.
This info is from an impeccable source.
You should save your window variable in Vue.prototype
main.js
Vue.prototype.$authUser = window.authUser;
After that, you can access your data as follows:
Vue template
<div v-text="$authUser.name"></div>
Vue script
let name = this.$authUser.name;
window is available in the vuex store. This may help if you need to mutate the window property synchronously with other actions/mutations, give you a chance to validate what goes into it, or catch an error if the variable you intend to put there isn't available.
export default new Vuex.store({
state: {
windowFoo: window.foo,
googleRecaptcha: window.google_recaptcha_public_key
},
getters: {
windowFoo: (state) => state.windowFoo,
googleRecaptcha: (state) => state.googleRecaptcha
},
actions: {
barThenFooThenBaz({ commit }, { foo }) {
// ... do some other required actions first
commit("setWindowFoo", foo);
// ... do some dependent actions next
}
},
mutations: {
setWindowFoo(state, foo) {
state.windowFoo = foo;
}
}
});
Then from your Single File Component...
//....
computed: {
windowFoo() {
return this.$store.getters.windowFoo;
},
googleRecaptcha() {
return this.$store.getters.googleRecaptcha;
}
},
methods: {
async barThenFooThenBaz(foo) {
await this.$store.dispatch({
type: "barThenFooThenBaz",
foo: foo
});
// ... do something dependent on windowFoo being set
}
}
//....
Although the other answers here are totally acceptable, I've had issues using the Vue instance with Vue.prototype in main.js as our project has gotten larger, so I hope this helps!
Provide/Inject works nicely. Here's an example with Vue 3:
main.js
const app = createApp(App)
app.provide('recaptcha_key', window.google_recaptcha_public_key)
app.mount('#app')
MyComponent.vue
<script setup>
const { inject } from 'vue'
const recaptchaKey = inject('recaptcha_key')
</script>
While trying out Vue and Vuex, i stumbled upon the following error message:
[Vue warn]: Property or method "msg" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
I fail to understand and solve this issue, mainly because msg is defined in the code under data. It's probably doesn't related directly to Vuex, but i faced it only when i started using Vuex.
Here is my code:
main.js:
import Vue from 'vue'
import App from './App.vue'
import { store } from './store.js'
Vue.component('app', App);
var vApp = new Vue({
el: '#app',
store,
render: h => h(App),
})
App.vue:
<template>
<div id="app">
<div v-text="msg"></div>
<input id="name-b" class="input" v-model="nameB" type="text" placeholder="Name B">
</div>
</template>
<script type = "text/javascript">
module.exports = {
name: 'app',
data() {
return {
msg: 'boooo'
}
},
computed: {
return {
nameB: {
get() {
this.$store.state.nameB
},
set(value) {
this.$store.commit('setName', value);
}
},
}
</script>
<style>
</style>
store.js:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
nameB: '',
},
mutations: {
setName: function(state, name) { state.locationName = name},
},
});
Thanks.
Problem solved.
It was a curly brackets issue and possibly the return in computed that is not needed...
This is a confusing error message.
Everything is fine in my main.js
import User from './components/User.vue'
new Vue({
el: '#user',
render: h => h(User),
data() {
return {
groups: []
}
},
mounted() {
this.getGroups();
},
methods: {
getGroups: function () {
axios.get('http://vagrant.dev/groups')
.then(response => this.groups = response.data)
.catch(error => console.log(error));
}
}
});
User.vue
<template>
<div id="user">
{{groups}} <!-- must be printed but it doesn't seem -->
</div>
</template>
<script>
export default {
name: 'user',
props: ['groups']
}
</script>
and index.html
<div id="user">
<user :groups="groups"></user>
</div>
Where is the mistake?
I do not get any errors, but I didn't understand why the value was not printed on the screen
Seems like you are putting 2 Vue instances on the same template since in your main file you are defining the template as el: "#user" which is already controlled by User.vue.
In you index.html add a div with id="app" and in main.js set el: "#app"
Your main.js and index.html shouldn't mix template in HTML and render function. So your main.js should be:
```new Vue({
el: '#user',
components: { User },
data() {
return {
groups: []
}
},
...```
You shouldn't directly reassign data value because Vue cannot detect property additions and rerender view. You should do it via Vue.set or this.$set like this:
this.$set(this, 'groups', response.data)
You can read more about how vue reactive in https://v2.vuejs.org/v2/guide/reactivity.html and Vue.set API: https://v2.vuejs.org/v2/api/#Vue-set
In my app, I have a template for things like Invoice, Email etc. I'd like the user to be able to edit these templates by dragging and dropping elements. I'm currently using vue-loader along with webpack to pre-compile my vue files into pure JS.
Is it possible to load a vue template from the database on the fly? I've seen this post but this isn't using vue-loader so I'm not sure how to override the template on my component via the code. Something like:
created: function () {
this.$template = '<html><p>Loaded from the DB!</p></html>'
}
would be useful. Is this possible?
Edit: I've tried the following but I get an error Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.:
created: function () {
document.body.innerHTML = '<html><p>I AM FROM THE DB {{total}}</p></html>'
}
This would need to be modified to pass in the templates from your database, but this works in a very simple single file component. Obviously you will want to customize, but this demonstrates the concept.
Dynamic.vue
<script>
export default {
props:["template"],
data(){
return {
message:"hello"
}
},
created(){
this.$options.template = this.template
}
}
</script>
App.vue
<template>
<div>
<dynamic
v-for="template, index of templates"
:template="template" :key="index">
</dynamic>
</div>
</template>
<script>
import Vue from "vue"
import Dynamic from "./Dynamic.vue"
export default {
name: 'app',
data () {
return {
templates: [
"<h1>{{message}}</h1>",
"<h4>{{message}}</h4>"
]
}
},
components:{
Dynamic
}
}
</script>
main.js
import Vue from 'vue'
import App from './App.vue'
new Vue({
el: '#app',
render: h => h(App)
})