Vue series eight: computed properties, content distribution, custom events

1. What is a computed property

The focus of the computed property is on 属性two words (property is a noun), firstly it is a capability (computation is a verb), here is a function: simply put, it is a function that can cache the results of computation Attributes (converting behavior into static attributes), nothing more; think of it as a cache! The code above属性计算计算
  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--view层,模板-->
<div id="app">
    <p>currentTime1:{
   
   {currentTime1()}}</p>
    <p>currentTime2:{
   
   {currentTime2}}</p>
</div>

<!--1.导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript">
    var vm = new Vue({
        el:"#app",
        data:{
          message:"pan"
        },
        methods:{
            currentTime1:function(){
                return Date.now();//返回一个时间戳
            }
        },
        computed:{
            currentTime2:function(){//计算属性:methods,computed方法名不能重名,重名之后,只会调用methods的方法
                this.message;
                return Date.now();//返回一个时间戳
            }
        }
    });
</script>
</body>
</html>

Note: things in methods and computed cannot have the same name
Description:

  • methods: define a method, use currentTime1() to call the method, need parentheses

  • computed: define the computed property, call the property using currentTime2, without parentheses: this.message changes in order to allow currentTime2 to observe data changes

  • How to change the value in the method, the cache will be refreshed! You can use it in the console vm.message=”q in jiang", change the value of the data, and test the observation effect again!

    Conclusion:
      When calling a method, you need to talk about the calculation every time. Since there is a calculation process, there will be system overhead. What if the result does not change frequently? At this time, you can consider caching the result, and using calculated properties can It is very convenient to do this. The main feature of the computed property is to cache the calculation results that change infrequently to save our system overhead;

8.2. Content distribution

In Vue.js, we use the <slot>element as the outlet to carry the distributed content, the author calls it a slot, which can be used in the scene of combining components;

test

For example, you are going to make a todo component (todo), which consists of todo title (todo-title) and todo content (todo-items), but these three components are independent of each other, how to operate?
  The first step is to define a to-do component

<div id="app">
    <todo></todo>
</div>
<!--1.导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript">
    Vue.component('todo',{
        template:'<div>\
                <div>代办事项</div>\
                <ul>\
                    <li>学习狂神说Java</li>\
                </ul>\
            </div>'
    })
</script>

In the second step, we need to dynamically bind the title and value of the to-do item. How to do it? We can leave a slot!
  1- Leave the code above with a slot, the slot

 Vue.component('todo',{
        template:'<div>\
                <slot name="todo-title"></slot>\
                <ul>\
                    <slot name="todo-items"></slot>\
                </ul>\
            </div>'
    });

2- Define a todo title component called todo-title and todo content component todo-items

Vue.component('todo-title',{
        props:['title'],
        template:'<div>{
   
   {title}}</div>'
    });
   
12345
//这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来!
    Vue.component("todo-items",{
        props:["item","index"],
        template:"<li>{
   
   {index+1}},{
   
   {item}}</li>"
    });

3- Instantiate Vue and initialize data

 var vm = new Vue({
        el:"#vue",
        data:{
            todoItems:['test1','test2','test3']
        }
    });

4- Insert these values ​​through the slot

<div id="vue">
    <todo>
        <todo-title slot="todo-title" title="秦老师系列课程"></todo-title>
        <!--<todo-items slot="todo-items" v-for="{item,index} in todoItems" v-bind:item="item"></todo-items>-->
        <!--如下为简写-->
        <todo-items slot="todo-items" v-for="item in todoItems" :item="item"></todo-items
    </todo>
</div>

Description: Our todo-title and todo-items components are distributed to the todo-title and todo-items slots of the todo component, respectively. The
  complete code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--view层,模板-->
<div id="vue">
    <todo>
        <todo-title slot="todo-title" title="title"></todo-title>
        <!--<todo-items slot="todo-items" v-for="{item,index} in todoItems" v-bind:item="item"></todo-items>-->
        <!--如下为简写-->
        <todo-items slot="todo-items" v-for="item in todoItems" :item="item"></todo-items
    </todo>
</div>
<!--1.导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript">
    Vue.component('todo',{
        template:'<div>\
                <slot name="todo-title"></slot>\
                <ul>\
                    <slot name="todo-items"></slot>\
                </ul>\
            </div>'
    });
    Vue.component('todo-title',{
        props:['title'],
        template:'<div>{
   
   {title}}</div>'
    });
    //这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来!
    Vue.component("todo-items",{
        props:["item","index"],
        template:"<li>{
   
   {index+1}},{
   
   {item}}</li>"
    });

    var vm = new Vue({
        el:"#vue",
        data:{
            title:"秦老师系列课程",
            todoItems:['test1','test2','test3']
        }
    });
</script>
</body>
</html>

8.3. Custom events

Through the above code, it is not difficult to find that the data item is in the instance of Vue, but the deletion operation must be completed in the component, so how can the component delete the data in the Vue instance? At this time, parameter transmission and event distribution are involved. Vue is We provide the function of custom event to help us solve this problem; using this.$emit('custom event name', parameter), the operation process is as follows:
  1-Add the methods object to the instance of vue and defines a method called removeTodoltems

var vm = new Vue({
        el:"#vue",
        data:{
            title_text:"秦老师系列课程",
            todoItems:['test1','test2','test3']
        },
        methods:{
            removeItems:function(index){
                console.log("删除了"+this.todoItems[index]+"OK");
                //splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目,其中index
                this.todoItems.splice(index,1);
            }
        }
    });

2- Modify the code of the todo-items to-do content component, add a delete button, and bind the event!

 Vue.component("todo-items",{
        props:["item_p","index_p"],
        template:"<li>{
   
   {index_p+1}},{
   
   {item_p}} <button @click='remove'>删除</button></li>",
        methods:{
            remove:function (index) {
            //这里的remove是自定义事件名称,需要在HTML中使用v-on:remove的方式
                //this.$emit 自定义事件分发
                this.$emit('remove',index);
            }
        }
    });

3- Modify the HTML code of the todo-items to-do content component, add a custom event, such as remove, which can be bound to the component's method, and then bound to the vue method!

<!--增加了v-on:remove="removeTodoItems(index)"自定义事件,该组件会调用Vue实例中定义的-->
<todo-items slot="todo-items" v-for="(item,index) in todoItems"
                    :item_p="item" :index_p="index" v-on:remove="removeItems(index)" :key="index"></todo-items>

Modify the previous code to implement the delete function

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--view层,模板-->
<div id="vue">
    <todo>
        <todo-title slot="todo-title" :title="title_text"></todo-title>
        <!--<todo-items slot="todo-items" v-for="(item,index) in todoItems" v-bind:item="item"></todo-items>-->
        <!--如下为简写-->
        <todo-items slot="todo-items" v-for="(item,index) in todoItems"
                    :item_p="item" :index_p="index" v-on:remove="removeItems(index)" :key="index"></todo-items>
    </todo>
</div>
<!--1.导入Vue.js-->
<script src="../js/vue.js"></script>
<script type="text/javascript">
    Vue.component('todo',{
        template:'<div>\
                <slot name="todo-title"></slot>\
                <ul>\
                    <slot name="todo-items"></slot>\
                </ul>\
            </div>'
    });
    Vue.component('todo-title',{
        props:['title'],
        template:'<div>{
   
   {title}}</div>'
    });
    //这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来!
    Vue.component("todo-items",{
        props:["item_p","index_p"],
        template:"<li>{
   
   {index_p+1}},{
   
   {item_p}} <button @click='remove_methods'>删除</button></li>",
        methods:{
            remove_methods:function (index) {
                //this.$emit 自定义事件分发
                this.$emit('remove',index);
            }
        }
    });

    var vm = new Vue({
        el:"#vue",
        data:{
            title_text:"秦老师系列课程",
            todoItems:['test1','test2','test3']
        },
        methods:{
            removeItems:function(index){
                console.log("删除了"+this.todoItems[index]+"OK");
                this.todoItems.splice(index,1);
            }
        }
    });
</script>
</body>
</html>

logical understanding

 

8.4, Vue entry summary

Core: data-driven, componentized

Advantages: Drawing on the modular development of AngularJS and the virtual Dom of React, the virtual Dom is to put the Demo operation into memory for execution;

Common properties:

  • v-if
  • v-else-if
  • v-else
  • v-for
  • v-on binding event, shorthand @
  • v-model data two-way binding
  • v-bind binds parameters to components, shorthand:

Componentization:

  • Combination component slot
  • Binding events inside components needs to be usedthis.$emit("事件名",参数);
  • Features of computed properties, caching computed data

Following the principle of SoC separation of concerns, Vue is a pure view framework and does not include communication functions such as Ajax. In order to solve the communication problem, we need to use the Axios framework for asynchronous communication;

illustrate

The development of Vue is based on NodeJS. The actual development uses Vue-cli scaffolding development, vue-router routing, and vuex for state management; Vue UI, we generally use ElementUI (produced by Ele.me) or ICE (produced by Alibaba) Let's quickly build a front-end project~~

Official website:

  • https://element.eleme.cn/#/zh-CN
  • https://ice.work/

Guess you like

Origin blog.csdn.net/qq_21137441/article/details/123768219