Textarea v-model initial value with VueJS and Laravel

狂风中的少年 提交于 2019-12-22 09:58:26

问题


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


回答1:


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/




回答2:


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: {

      }
  })  
}


来源:https://stackoverflow.com/questions/49767714/textarea-v-model-initial-value-with-vuejs-and-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!