[Vuejs]-How to seperate Vue logic in a laravel app based on layout and page templates

0๐Ÿ‘

โœ…

I found out how to do it. The trick was to use an inline template. Surround the form in the view with:

<object-form inline-template>
    <form>...</form>
</object-form>

Where object-form is the name of the component. In the ObjectForm code above I remove the template, like this:

var ObjectForm = {
    data: function() {
        return {
            selectedOption: 1
        }
    },
    computed: {
        displayField: function() {
            // return true or false depending on form state
            return true;
        }
    }
};

I attach the component within the root vue app like this:

const app = new Vue({
    el: 'body',
    components: {
        'object-form': ObjectForm
    }
});

This way I can use the form as it was generated from the controller and view and I can separate it from the root (attached to body) methods and properties.

To organize it even better I can probably store the ObjectForm in a seperate .vue file the way @Tayler Foster suggested.

0๐Ÿ‘

I hope this helps kind of break things down for you and helps you understand Vue templating.

It is best to take advantage of Vueโ€™s components. For you it would look something like this. Some of this code depends on your file structure, but you should be able to understand it.

In your app.js file (or your main js file)

Vue.component('myform',require('./components/MyForm.vue'));

const app = new Vue({
  el: "#app"
});

Then create the MyForm.vue file

<template>
 <form> 
  Put Your Form Markup Here
 </form>
</template>

<script>
 // Here is where you would handle the form scripts.
 // Use methods, props, data to help set up your component
  module.exports = {
    data: function() {
        return {
            selectedOption: 1
        }
    },
    computed: {
        displayField: function() {
            // return true or false depending on form state
            return true;
        }
    },
   methods: {
     // add methods for dynamically changing form values
   }
  }
</script>

Then you will be able to just call in your blade file.

<myform></myform>

Leave a comment