Textarea v-model initial value with VueJS and Laravel

Prasanna Kumar picture Prasanna Kumar · Apr 11, 2018 · Viewed 11.5k times · Source

I want to display the username as the default textarea value for markdown editor using blade syntax.

<textarea v-model="message">
      {{ $detailsFromLaravelContoller }}
</textarea>
<div v-html="compiledMarkdown"></div>

But I am using v-model component for the textarea which requires to declare message with an empty value like this

window.onload = function()
{ 
    var editor = new Vue({
    el: '#editor',
    data: {
        message: '',
        compiledMarkdown: marked('', { sanitize: true }), 
    },
    watch: {
        markdown: function () {
          this.compiledMarkdown = marked(this.message, { sanitize: true })
        }
      }, 
      methods: {

      }
  })  
}

This renders the screen with the laravel variable's value. But soon after the page loads the content disappears (as I've used window.onload I guess).
Also I'm not using inline VueJS.
P.S: I'm new to both VueJS and Laravel and the source for the markdown is here(jsfiddle)
Thank you in advance!!!

Answer

Jacob Goh picture Jacob Goh · Apr 11, 2018

You are trying to pass a PHP variable value to a separate Javascript file.

Here's how I would do it:

Declare a global variable detailsFromLaravelContoller to store $detailsFromLaravelContoller as a string value

<script>
    var detailsFromLaravelContoller = @json($detailsFromLaravelContoller);
</script>
<textarea v-model="message">
</textarea>

use the global variable in Javascript file

data: {
    message: detailsFromLaravelContoller,
},

https://jsfiddle.net/jacobgoh101/0dzvcf4d/9954/