Vue front-end Js framework

To put it simply, Vue is a set of MVVM framework for Javascript. This framework allows us to separate layout and view, reduce data mud, and is also a more practical framework for component development. If you have learned Android's DataBinding framework before , you can try to follow the thinking. Without further ado, here is how the framework is used:

1. Download the source code

First of all, you can find the hosted code on github , or you can learn about it through the official website . It is recommended that readers learn this set of courses first, and then continue to learn more through the official website.

1. Open the official website, click on the tutorial
on the navigation 2. Click Install
3. If you install it, you can save vue.js directly as a save, or you can download it through the mpn command

npm install vue 

4. After the download is successful, a node_modules folder will appear, copy /vue/dist/vue.js (and vue.min.js ) to our project.

2. The new project introduces the development kit

Here I use WebStorm for development. My project directory is as follows:
write picture description here

3. The principle of vue

The core of vue is ViewModel, and its schematic diagram is as follows:
write picture description here

The above schematic diagram is mainly divided into three parts:
DOM: It refers to the Dom tree formed by Html tags. That is, each label is a part of Dom, and operating Dom is to operate the view area of ​​Html.
JavaScript Objects: Represents data data.
Vue: also our core, called ViewModel. In general, the direct mixing of the view area and the data can easily cause data confusion, so you can think that the ViewModel is equivalent to a bridge between the two. Changes in data will lead to changes in views, and operations on views can also directly manipulate data.

4. A Simple Example

Now that we understand the principle, let's write an h5 page with the following code:

<body>
        <script src="../js/vue.js"></script>
    <!-- 1.创建一个需要被操作的视图盒子 -->
    <div id="box1">
        <!-- 6.引用字符串message -->
        <p>{{message}}</p>
        <!-- 7.v-model指定输入框引用字符串message -->
        <input v-model="message">
    </div>

    <script>
        /*2.创建一个ViewModel实例*/
        var vm=new Vue({
            /*3.关联视图区*/
            el:"#box1",
            /*4.关联数据区 数据区内可以指定多个数据*/
            data:{
                /*5.声明了一个字符串message*/
                message:"hello world !"
            }
        });
    </script>

</body>

5. Vue instruction learning

Some simple instruction sets are introduced below. If you want to learn more, you can check the official website Api .

v-text directive

Remember the code above refers to a string?

<p>{{message}}</p>

We can write this with the v-text directive:

<p v-text='message'/>


v-once directive

<!-- 6.引用字符串message -->
<p>{{message}}</p>
<!-- 7.v-model指定输入框引用字符串message -->
<input v-model="message">

In the above example, since both the p tag and the input tag refer to the same string message, as long as the text of the input box changes, the data corresponding to the p tag will also change. And if the v-once directive is added, then the p tag will only display the string of the first assignment:

<p v-once>{{message}}</p>
<input v-model="message" />


v-if directive

The v-if instruction represents a condition, that is, the boolean value of js can decide to implement certain operations. For example, we can decide to display the user's identity according to the boolean value of js:

<body>
    <div id="box1">
        <p v-if="isVip">Vip尊贵会员</p>
        <p v-if="!isVip">普通会员</p>
    </div>
    <script>
        var vm=new Vue({
            el:"#box1",
            data:{
                isVip:true
            }
        })
    </script>
</body>

v-show command

The operation of the v-show command is similar to that of the v-if command. Both can decide whether to display a label according to the boolean value. The above code has the same effect after modification. The code is as follows:

<div id="box1">
    <p v-show="isVip">Vip尊贵会员</p>
    <p v-show="!isVip">普通会员</p>
</div>

So what's the difference between them?

The rendering effect using the v-if instruction is like this, that is, it decides which label to display according to the conditions, and only one is displayed:
write picture description here



Using the v-show instruction, it can be seen from the source code that he actually renders multiple tags, and then decides whether to hide it according to css:
write picture description here


v-else-if and v-else directives

<div id="box1">
    <p v-if="userLevel==0">普通用户</p>
    <p v-else-if="userLevel==1">铜牌会员</p>
    <p v-else-if="userLevel==2">银牌会员</p>
    <p v-else>金牌会员</p>
</div>
<script>
    var vm=new Vue({
        el:"#box1",
        data:{
            /*
            * 0:普通用户
            * 1:铜牌会员
            * 2:银牌会员
            * 3:金牌会员
            * */
            userLevel:1
        }
    })
</script>


v-for directive

With the enhanced for loop type in java, the socre variable is created in the following reference, then the following tags can be used:

<div id="box1">
    <p v-for="socre in scores">身高:{{socre}}</p>
</div>
<script>
    var vm=new Vue({
        el:"#box1",
        data:{
           scores:[
                   99,85,40,66,78
           ]
        }
    })
</script>

The effect diagram is posted below:
write picture description here

We can even assemble a series of data returned from the background into a table, the code is as follows:

<head>
    <meta charset="UTF-8">
    <title>07_Vue常见指令v-for</title>
    <script src="../js/vue.js"></script>
    <style type="text/css">
        *{
            margin:0px;
            padding:0px;
        }
        table{
            width:600px;
            border:solid 2px pink;
            text-align: center;
        }
        thead{
            font-weight:bold;
            background-color: red;
        }
    </style>
</head>
<body>
    <div id="box1">
        <table >
            <thead>
                <tr>
                    <td>姓名</td>
                    <td>年龄</td>
                    <td>身高</td>
                </tr>
            </thead>
            <tbody>
                <tr v-for="person in persons">
                    <td>{{person.name}}</td>
                    <td>{{person.age}}</td>
                    <td>{{person.height}}</td>
                </tr>
            </tbody>
        </table>
    </div>
    <script>
        var vm=new Vue({
            el:"#box1",
            data:{
               persons:[
                   {name:"张三",age:20,height:17.5},
                   {name:"李四",age:22,height:18},
                   {name:"王五",age:24,height:1.63},
               ]
            }
        })
    </script>
</body>

write picture description here

v-bind directive

In the above process, we will assign simple text data. The operation of other attributes except text data is unsuccessful. For example, the following code writes the address of the picture in vue, and the assignment is unsuccessful. :

<div class="box1">
    <img src="imgSrc" alt="tupian" />
</div>

<script>
    var vm=new Vue({
        el:".box1",
        data:{
            imgSrc:"../img/logo.png",
        }
    })
</script>

Solution A:

<img v-bind:src="imgSrc" alt="tupian" />

After this setting, it can be displayed directly. If you find that v-bind is red in the editor, you can download a plugin called vue.

Solution B:

<img :src="imgSrc" alt="tupian" />

The above code v-bind can be ignored, the default is v-bind as written above.

v-on command

The v-on command is a command for click events. Like the v-bind command, there are two ways to write it (comment/non-comment):

<div class="box1">
    <!--
    <p v-text="tip"
       v-on:click="clickImg('提示被点击了!')" />
    -->
    <p v-text="tip"
       @click="clickImg('提示被点击了!')" />
</div>

<script>
    var vm=new Vue({
        el:".box1",
        data:{
            imgSrc:"../img/logo.png",
            tip:"提示", 
        },
        methods:{
            clickImg(str){
                alert(str);
            }
        }
    })
</script>

6. Componentization

Componentization can reuse our interface components. Another major advantage of Vue is componentization, which can be used in two ways: global components & local components. Global components are components that can be used on the entire page, and local components Components are associated with each ViewModel instance. The two creation methods are described below.

Open the JD interface, you can see the following figure, the interface modules here are similar, we can create a unified template for processing.
write picture description here

1. Global componentization

Global componentization is divided into 3 steps: creating a constructor, registering components, and using components, as follows:

<body>
    <div id="box1">
        <!-- 3.使用组件 -->
        <st></st>
    </div>
    <script>
        //1.创建构造器
        var Profile=Vue.extend({
           template:'<h1>这是一个简单的标题!</h1>'
        });
        //2.注册组件
        Vue.component("st",Profile);
        new Vue({
            el:"#box1"
        })

    </script>
</body>

You can also simplify it like this:

<body>
    <div class="box1">
        <!-- 3.使用组件 -->
        <st></st>
    </div>
    <script>

        //1.创建构造器
        //2.注册组件
        Vue.component("st",{
            template:'<h1>Hello Simple Title</h1>'
        })
        new Vue({
            el:'.box1'
        })
    </script>
</body>

2. Local componentization

Local variables are bound to a ViewModel instance, the code is as follows:

<body>
    <div id="box">
        <haha></haha>
    </div>
    <script>
        var Profile=Vue.extend({
            template:"<h1>这是一个简单的局部标题</h1>"
        });
        new Vue({
            el:"#box",
            components:{
                "haha":Profile
            }
        })
    </script>
</body>

Simplified writing is as follows:

<body>
    <div id="box">
        <haha></haha>
    </div>
    <script>
        new Vue({
            el:"#box",
            components:{
                "haha":{
                    template:"<h1>简单创建的方式</h1>"
                }
            }
        })
    </script>
</body>

3. Subcomponentization

A component can be composed of many sub-components. I believe that students who have studied mobile development are relatively clear. Here is how to use sub-components:

<body>
    <div id="box1">
        <haha></haha>
    </div>
    <script>
        var childProfile=Vue.extend({
            template:'<img src="../img/logo.png"/>'
        });
        var parentProfile=Vue.extend({
            components:{
                "childT":childProfile
            },
            template:'<div><childT></childT><p>模糊的照片</p></div>'
        })

        Vue.component("haha",parentProfile);

        new Vue({
            el:"#box1"
        })

    </script>
</body>

4. Templating using template and script tags

The components we created earlier all have a unified set of template code, but the readability of the template code is very poor. The new way of writing the template is introduced as follows:

<div id="box">
    <my-component></my-component>
    <script-component></script-component>
</div>

<template id="component_id">
    <h1>这是一个简单的template标题</h1>
</template>

<script type="text/template" id="script_id">
    <h1>这是一个简单的script标题</h1>
</script>

<script>

    //注册一个组件
    Vue.component("my-component",{
        template:'#component_id'
    });

    //注册一个组件
    Vue.component("script-component",{
        template:'#script_id'
    });

    new Vue({
        el:'#box'
    });

</script>

5. Get the internal data of the component

If we want to get the data of the internal instance of Vue, we can declare it in the data code block inside Vue, but in the component constructor, if we want to provide data to the outside world, we use a function instead of a code block, and we can return the data that needs to be returned. The data will be returned in the form of JSON that needs to be provided.

As follows, our component provides a data called message, as follows:

  <div id="box">
    <my-component></my-component>
  </div>

  <template id="cp_template">
    <h1>{{message}}</h1>
  </template>

  <script>
    var Profile=Vue.extend({
      template:'#cp_template',
      //组件中提供的数据需要通过函数返回
      data(){
        return {
          message:'这是函数里面的数据'
        }
      }
    });
    Vue.component("my-component",Profile);

    new Vue({
      el:"#box"
    });
  </script>

6. The component provides external property configuration

In order to make the components we created more general, we can provide relevant configuration to the client through attributes. As follows, we let the client set the corresponding argument attribute value and print the content of the value in the component:

<div id="box">
    <my-component argument="hello参数"></my-component>
</div>
<template id="cp_tmp" >
    <h1>这是组件模板中的一个简单的标题 {{argument}}</h1>
</template>
<script>
    Vue.component("my-component",{
        props:["argument"],
        template:'#cp_tmp'
    });
    new Vue({
        el:'#box'
    });
</script>

Props can specify and declare one or more property names. Of course, when components are nested with each other, the following describes how nested components provide properties to the outside world. Note that for properties that are not text, dynamic binding is required.

<div id="box">
    <parent-component :imgsrc="imgSrc" title="title"></parent-component>
</div>

<template id="child_id">
    <img :src="imgsrc" />
</template>

<template id="parent_id">
    <div>
        <my-child :imgsrc="imgsrc"></my-child>
        <br>
        <h1>{{title}}</h1>
    </div>
</template>
<script>

    var child =Vue.extend({
        props:["imgsrc"],
        template:'#child_id'
    });

    var parent =Vue.extend({
        props:["imgsrc","title"],
        template:'#parent_id',
        components:{
            "my-child":child
        }
    });

    Vue.component("parent-component",parent);

    new Vue({
        el:"#box",
        data:{
            imgSrc:"../img/logo.png",
            title:"这是一个标题"
        }
    });
</script>

7. Click event under component nesting

In the above property development, we found that the properties are passed from the parent component to the inside, and the click event is passed from the child component to the parent component. Here we do it through the v-on directive and vue.$emit().

Next, we use a child component click event to control the data inside the parent component. The effect diagram is as follows:
write picture description here

code show as below:

<div id="box">
    <parent></parent>
</div>
<template id="child_id">
    <button @click="countData">{{counter}}</button>
</template>
<template id="parent_id">
    <div>
        <p>{{totalCounter}}</p>
        <child @countevent="calculate()"></child>
        <child @countevent="calculate()"></child>
        <child @countevent="calculate()"></child>
    </div>
</template>
<script>

    Vue.component("child",{
        data(){
            return {
                counter:0
            }
        },
        template:"#child_id",
        methods:{
            countData(){
                this.counter+=1;

                //触发某个事件
                this.$emit('countevent');
            }
        }
    });

    Vue.component("parent",{
        data(){
            return {
                totalCounter:0
            }
        },
        template:"#parent_id",
        methods:{
            calculate(){
                this.totalCounter+=1;
            }
        }
    });

    new Vue({
       el:"#box"
    });
</script>

7. Use of styles

There are two types of style operations, one is to operate the style tag, and the other is to operate the class tag. Use as follows:

style tag

<body>
    <div id="box1">
        <p :style="pstyle">Style样式</p>
    </div>
    <script>
        new Vue({
            el:"#box1",
            data:{
                pstyle:{
                    backgroundColor: 'red',
                    textAlign: 'center',
                    fontSize: '22px'
                }
            }
        })
    </script>
</body>

class tag

<head>
    <meta charset="UTF-8">
    <title>15_子组件的应用</title>
    <script src="../js/vue.js"></script>
    <style>
        .normal{
            background-color: red;
        }
        .active{
            background-color: blue;
        }
    </style>
</head>
<body>
    <div id="box1">
        <p :class="isActive?'active':'normal'">class样式</p>
        <button @click="changeColor">改变颜色</button>
    </div>
    <script>
        new Vue({
            el:"#box1",
            data:{
                isActive:true
            },
            methods:{
                changeColor(){
                    this.isActive=!this.isActive;
                }
            }
        })
    </script>
</body>

8. Slots

In a component template, we want some layout that should be implemented by the client, at this point we can use the slots provided to us by Vue.

Slot: Just like our computer motherboard, the entire frame is fixed, but we can insert different types of sub-assemblies as needed.

There are two types of slots, anonymous slots and real-name slots.

anonymous slot

For example, I want to implement a small interface. The interface consists of three parts: the upper, middle and lower parts, and the middle part can be replaced. At this time, our code is as follows:

<div id="box1">
    <my-component>
        <!--客户端决定中间部分的内容 注意这里应该只有一个根标签-->
        <div>
            <img src="../img/logo.png" alt="">
        </div>
    </my-component>
</div>
<br>
<div id="box2">
    <my-component>
        <h1>Box2的内容</h1>
    </my-component>
</div>

<template id="my_component">
    <!--定义模板-->
    <div id="container">
        <h1 id="header">这是一个头部</h1>
        <slot>中间这部分由使用该组件的客户端决定显示需要的内容</slot>
        <h1 id="footer">这是一个底部</h1>
    </div>
</template>

<script>
    Vue.component("my-component",{
        template:"#my_component"
    });
    new Vue({
       el:"#box1"
    });

    new Vue({
        el:"#box2"
    });
</script>

real name slot

Anonymous slots are more in line with the need for only one slot in a template. And if a template needs multiple slots, you need to set a name for each slot, the code is as follows:

<div id="box">
    <my-component>
        <div slot="cpu">inter core i7</div>
        <div slot="gpu">xxx gpu</div>
        <div slot="memory">xxx 内存条</div>
        <div slot="storage">xxx 硬盘</div>
    </my-component>
</div>
<template id="component">
    <div id="container">
        <slot name="cpu">这是插入CPU</slot>
        <slot name="gpu">这是插入GPU</slot>
        <slot name="memory">这是插入MOMORY</slot>
        <slot name="storage">这是插入STORAGE</slot>
    </div>
</template>
<script>
    Vue.component("my-component",{
        template:'#component'
    });
    new Vue({
        el:"#box"
    });
</script>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326036149&siteId=291194637