The original

Laravel blade with jquery and Boostrap. Look at the front end of the Vue, try the new page, summarize the experience

  • Benefits: Forms are easier to manipulate, simplifying the logic of dynamically rendering pages.
  • Disadvantages: Previously used JS library, under the framework of Vue, there will be initialization problems. Right now it’s all inupdatedCallback reinitialization, do not know if it is the right way.
  • Unknown: Front-end automation tools and single file components have been useless. Mainly just write ~

Let the Vue work

When you see all the tools at the front, the head is big. The easiest way to use Vue is to import vue.min.js directly, just like any other JS library. You can then create a Hello World page using the official example. That’s it. We’re ready. Then we have to start to change the concept, before has been Laravel, so the front page is also more dependent on Laravel related. With Vue, we have to force the separation of the front and back ends, and all the data is temporarily accessed by JS

QA

Symbolic conflicts

Vue_variable %> {vue_variable %> {vue_variable %> {vue_variable %> {vue_variable %> {vue_variable %>

var hotelController = new Vue({
    el:'#hotelEl',
    delimiters: ["< %"."% >"],... })Copy the code

Loading initial data

The first question I encountered was when to send a page data request and how to control the loading state of the page at the beginning

  1. [V-cloak] controls the Vue initialization page, otherwise the page will always see a Vue variable before the Vue initialization
  2. Define a loading variable to control the loading state. After the page data is requested, set loading to false.
  3. Make the data request in the Created callback, using AXIos to make the request

A Post request

This is probably the most convenient part of VUE for me. I simply post data in Vue without worrying about the field design in the form. The backend handles the JSON parameters directly

update_data : function(){
    var paras = JSON.parse(JSON.stringify(this.$data));//covert data to json
    axios.post(url,paras.hotel)
        .then(function(response){
            //parse response
        })
        .catch(function(error){
            //console.log(error)
        });
}
Copy the code

The dynamic form

The idea was to construct a form string using Jquery and append it to the corresponding div. Splice (index, 0, empty) or arr.splice(index,1) to change the size of the array and control the number of forms

Child controls pass data

Parent to child is defined through props, and child to parent is passed through emit events

    <z-float-input-district 
    dom_id="district" 
    placeholder="Area" 
    name="district"
    v-model="hotel.location.district" 
    v-on:district_select="event_district">
    </z-float-input-district>
                                
                                
    Vue.component('z-float-input-district',{
        props:["placeholder","name", "value", "dom_id"],
        template: '<label class="form-group has-float-label">' +
        '<input :id="dom_id" class="form-control form_input" :name="name" :placeholder="placeholder" ' +
        'v-bind:value="value"' +
        'v-on:input="update($event.target.value)"/>' +
        '<span><% placeholder %></span>',
        mounted:function(){
            //...
        },
        data : function(){
            return {
                //...
            }
        },
        methods: {
            update:function(item){
                if(item.hasOwnProperty("district")){
                    this.$emit('input', item.district)
                    this.$emit('district_select', item)
                }
            }
        }
    });
Copy the code

Jquery modified form form, if synchronized to Vue data

In general, when a user enters a modified form, it is possible to implement two-way binding via the V-Model. However, due to some lingering issues, you still need to modify the form data via Jquery or code, such as using a date-range-picker third-party control. This is where the native event notification Vue needs to be constructed.

helper_js_event : function(obj){
    var evt = document.createEvent('HTMLEvents');
    evt.initEvent('input'.false.true);
    obj.dispatchEvent(evt);
}
Copy the code

When an input is modified using Jquery, call helper_js_event(INPUT) to synchronize it to Vue

Forced to refresh

$forceUpdate(); this.$forceUpdate();

Copy the data

A clone function is required, but the data in Vue’s data is copied. Object and ARR are deep copy, so it is awkward to implement a clone function by itself

   function clone(obj) {
        var copy;
        if (null == obj || "object"! =typeof obj) return obj;

        if (obj instanceof Date) {
            copy = new Date(a); copy.setTime(obj.getTime());return copy;
        }
        if (obj instanceof Array) {
            copy = [];
            for (var i = 0, len = obj.length; i < len; i++) {
                copy[i] = clone(obj[i]);
            }
            return copy;
        }
        if (obj instanceof Object) {
            copy = {};
            for (var attr in obj) {
                if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
            }
            return copy;
        }

        throw new Error("Unable to copy obj! Its type isn't supported.");
    }
Copy the code

Check to see if the page is saved when it returns

Because the form data is more, to prevent the loss of content, do a ask whether to save the function.

As for why not automatic save, afraid of the error operation automatic save can not go back…

Originally, I wanted to monitor the changes of Vue data through Watch, but I found something wrong, that is, watch would be called twice after Vue data was assigned, so I couldn’t judge the initial state of data. However, a simple variable behavior of my watch was correct, maybe the structure of data was too complicated.

Unsolved solutions, by comparing the JSON string to judge

// Call last_json = this.helper_hotel_json() after each successful save.
window.addEventListener("beforeunload".function (e) {
        if(last_json ! = hotelController.helper_hotel_json()){var confirmationMessage = 'Please make sure to save before leaving, otherwise the change information will be lost!! ';
            (e || window.event).returnValue = confirmationMessage; //Gecko + IE
            return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.}});Copy the code

Parsing route parameters

Vue-router is required, which I use mainly to parse URL parameters and get some configuration information

var router = new VueRouter({
        mode: 'history'.routes: []});var hotelList = newVue({ router, ... .created:function () {
            var hotel_id = this.$route.query.id; })}Copy the code

The for loop

<div v-for="(item, index) in items"> <% item %> </div> <div v-for="index in 7"> <% index %> </div> <template v-for="(item, index) in items"> <div> <% item %> </div> <div V-if ="index % 4 == 3"></div> </template>Copy the code

Page size fit

Well, some controls have to fit the page size. Want to think or direct code to try ~ first

Of course, the H5 page is still written separately, and is generally redirected to the h5 page during PHP routing

mounted:function(){
    window.addEventListener('resize'.this.handle_resize)
    this.handle_resize(null);
},
beforeDestroy: function () {
    window.removeEventListener('resize'.this.handle_resize)
},
methods : {
    handle_resize : function(event){
        var height = document.documentElement.clientHeight;
        var width = document.documentElement.clientWidth;
        // Then you can manipulate data parameters that are related to the size of the interface}}Copy the code

Axios straddles the problem

Okay, this is too much work. I did it on the back end.

Use the previous third-party JS

The initialization timing of a third-party control. Currently, I check each updated callback. Otherwise there will be a failure problem.

  • Seven cow JS-SDK: Upload pictures
  • Affix: floating
  • Swiper: image gallery
  • Blueimp: Image Gallery & Fullscreen
  • Google Map: load asynchronously, so try to initialize it once when calling back

Refs

https://vuejs.org/