Laravel 5.6 and Vue Default values

1

I'm working on a project with Laravel 5.6 and Vue.js 2 that is costing me more than I thought.

I have read several articles and questions in this community and everywhere I have understood that it is normal to use components of Vue.js to pass values by default.

When using the Blade template engine to load a form, for example, we have the following form:

<form method="{{ action('Controlador@metodo', $modelo) }}">
    <input 
        type="text" 
        name="propiedad1"
        @if(old('propiedad1'))
        value="{{ old('propiedad1') }}"
        @elseif(isset($modelo) && $modelo->propiedad1)
        value="{{ $modelo->propiedad1 }}"
        @endif
        v-model="propiedad1"
        @focusout="miFuncion">
    <input 
        type="text" 
        name="propiedad2"
        @if(old('propiedad2'))
        value="{{ old('propiedad2') }}"
        @elseif(isset($modelo) && $modelo->propiedad2)
        value="{{ $modelo->propiedad2 }}"
        @endif
        v-model="propiedad2">
</form>

Well, for logical reasons (I think) the above does not work because we are mixing values that are put in the field before the DOM is created with fields that are created later.

The "simple" solution is to create a component, register it and adapt it ... But is not there an easier solution?

    
asked by Maramal 15.02.2018 в 20:41
source

1 answer

1

It is relative to say that it is easier or not, because that depends on each person.

To solve the problem you have several options, of which I am going to name a typical pair, hoping that one of these seems "easier":

  • a. Use templates inline

    link

    While you will not have the power to reuse the component with this method, you can do the entire process in your blade file:

    <my-component inline-template>
      <div>
        <p>These are compiled as the component's own template.</p>
        <p>Not parent's transclusion content.</p>
      </div>
    </my-component>
    

    b. X-templates

    Similar to the previous one, the template is defined in a tag <script> with type="text/x-template"

    <script type="text/x-template" id="hello-world-template">
      <p>Hello hello hello</p>
    </script>
    
    Vue.component('hello-world', {
      template: '#hello-world-template'
    })
    
  • Keep the component in an external file and pass the values that arrive from Laravel as "props" from Blade:

    Component Vue

    Vue.component('child', {
      props: ['message'],
      template: '<span>{{ message }}</span>'
    })
    

    Blade

    <child message="{{ $myVar }}"></child>
    

    Laravel driver (or whatever you call the view)

    $myVar = 'Hola';
    
    return view('message', compact('myVar'));
    
  • answered by 15.02.2018 / 23:46
    source