Search code examples
laravelvue.jsv-model

Textarea v-model initial value with VueJS and Laravel


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!!!


Solution

  • 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/