Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea v-model initial value with VueJS and Laravel

Tags:

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

like image 242
Prasanna Kumar Avatar asked Apr 11 '18 06:04

Prasanna Kumar


2 Answers

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/

like image 76
Jacob Goh Avatar answered Sep 28 '22 19:09

Jacob Goh


You can initialize the v-model in data with your laravel variable.

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

      }
  })  
}
like image 23
Agney Avatar answered Sep 28 '22 18:09

Agney