I am trying to pass a variable (here, externalVar) to a component, directly when initializing. But I can’t find how to do it (probably not understanding documentation well :/ ). What is the correct way to do it?
The initialization :
JavaScript
x
9
1
var externalVar = "hello world"
2
3
const leftmenu = new Vue({
4
el: "#left-menu",
5
template: "<CLM/>",
6
components: {CLM},
7
variableToPass: externalVar
8
});
9
The component I am initializing here is defined like this (getting back variableToPass in data):
JavaScript
1
18
18
1
<template src="./template-l-m.html"></template>
2
3
<script>
4
import draggable from 'vuedraggable';
5
export default {
6
name: 'leftmenu',
7
components: {
8
draggable
9
},
10
11
data () {
12
return {
13
jsonObject: this.variableToPass,
14
}
15
},
16
[ ]
17
</script>
18
But then , when I am trying to use this.jsonObject, it says that it’s undefined. What am I doing wrong ?
Advertisement
Answer
If i understand you correctly you want to use props to pass data to child components
Dynamically bind a prop attribute on child component element using :variable="variableToPass"
JavaScript
1
12
12
1
var externalVar = "hello world"
2
3
const leftmenu = new Vue({
4
el: "#left-menu",
5
template: "<CLM :variable='variableToPass'/>",
6
components: {CLM},
7
data: {
8
variableToPass: externalVar
9
}
10
11
});
12
Define a props option in the child component
JavaScript
1
18
18
1
<template src="./template-l-m.html"></template>
2
3
<script>
4
import draggable from 'vuedraggable';
5
export default {
6
name: 'leftmenu',
7
components: {
8
draggable
9
},
10
props: ['variable'],
11
data () {
12
return {
13
jsonObject: this.variable,
14
}
15
},
16
[ ]
17
</script>
18