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 :
var externalVar = "hello world" const leftmenu = new Vue({ el: "#left-menu", template: "<CLM/>", components: {CLM}, variableToPass: externalVar });
The component I am initializing here is defined like this (getting back variableToPass in data):
<template src="./template-l-m.html"></template> <script> import draggable from 'vuedraggable'; export default { name: 'leftmenu', components: { draggable }, data () { return { jsonObject: this.variableToPass, } }, [ ... ] </script>
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"
var externalVar = "hello world" const leftmenu = new Vue({ el: "#left-menu", template: "<CLM :variable='variableToPass'/>", components: {CLM}, data: { variableToPass: externalVar } });
Define a props option in the child component
<template src="./template-l-m.html"></template> <script> import draggable from 'vuedraggable'; export default { name: 'leftmenu', components: { draggable }, props: ['variable'], data () { return { jsonObject: this.variable, } }, [ ... ] </script>