Learn to use vue (notes)

1: vue basic syntax

1.1: basic data type and string

Value:
	{{code}}
	{{str}}

data:({
  code:100
  str:"test"
})

1.2: object data type

support ognl Syntax value:
	{{stu.name}}
	{{stu.age}}
data:({
  stu{
  	name:"zhangsan"
  	age:12
  }
})

1.3:if judgment statement

<div id="container">
    <label class="c" v-if="stu.gender=='M'">male</label>
    <label class="c" v-if="stu.gender=='S'">female</label>
</div>
var vm = new Vue({
    el:"#container",
    data:{
      stu:{
        name:"zhangsan",
        age:"16",
        gender:"S"
      }
    }
});

1.4: for loop statement

<div id="contriner">
  <table>
      <tr>
        <th>Serial number</th>
        <th>full name</th>
        <th>Gender</th>
        <th>Age</th>
      </tr>
      <tr v-for="s,index in stus">
        <td>{{index+1}}</td>
        <td>{{s.name}}</td>
        <td>{{s.age}}</td>
        <td>
          <label v-if="s.gender=='M'">male</label>
          <label v-if="s.gender=='S'">female</label>
     	 	</td>
      </tr>
  </table>
</div>
var vm = new Vue({
	el:"#container",
	data:{
      stus:[
                {
                  name:"zhangdasan",
                  age:"16",
                  gender:"S"
                },
                {
                  name:"zhangersan",
                  age:"19",
                  gender:"M"
                },
                {
                  name:"zhangsansan",
                  age:"21",
                  gender:"S"
              }
      ]
	}
})


1.5: v-bind: bind tag attribute

<div id="contriner">
	<input type="text" v-bind:value="str">
  <img :src="img">
</div>	

var vm = new Vue({
	el:"#container",
	data:{
      str:"biaoqianshuxing"
			img:"url"
	}
})

1.6: bidirectional binding of form labels

If you change the value in the input tag, the text in the label will also be changed

<input type="text" v-model:value="str">
<lable>
		{{str}}
</lable>

2.Vue life cycle

2.1:vue instance life cycle – the process from creation to destruction of vue instances

  • Create vue instance (initialize data, load el)
  • Data mount (rendering data from vue instance to HTML tag of web page)
  • Re rendering (when the data of vue changes, it will be re rendered into HTML tags)
  • Destroy instance (when page is closed)

Create object - property initialization - get property value - GC recycle

2.2: life cycle function

2.2.1 beforeCreate

Beforecreate: function ({}): before data initialization

2.2.2 created

Created: function ({}): after data initialization

2.2.3 beforeMount

Beforemount: function ({}): after data initialization. Before the template is loaded and the data is initially rendered (mounted), you can modify / obtain the value in the data, which will affect the v-once tag data

2.2.4 mounted

Mounted:function({}): after the initial rendering of the data, the data can be modified, but the data in the v-once tag will not be changed

2.2.5 beforeUpdate

beforeUpdate:function({}): not executed by default. After data rendering, re rendering is triggered when the data in the data changes. This function is triggered before rendering

After the data is modified, it is executed before the page is re rendered

2.2.6 updated

Updated: function ({}): after the data is modified, the page is re rendered and executed

2.2.7 beforeDestroy

Beforedestroy: function ({}): before Vue instance is destroyed

2.2.8 destroyed

Destroyed: function ({}): after the Vue instance is destroyed

3. Calculation attribute listener of Vue

The attributes in data can be obtained by name or calculated

Property: the value of the calculated property will be affected if the property on which the calculated property depends is changed

Listener: the listener in the data attribute. When the data value changes, it will trigger the execution of the listener function

4. class and style binding in Vue

We can use mustache syntax to bind the data in vue to html tags and tag attributes. How to bind the values in data to the class and style attributes of tags

4.1: class binding method I

<div :class="{'class1':boolean,'class-2':boolean}"></div>
<!-- class1 yes css Defined in class Name boolean yes vue example data Value in when boolean by true Bind this class for the tag, if false Unbound -->

4.2: class binding method 2

<div :class="[class1,class2]"></div>
<!--class1 and class2 yes data Values in -->

4.3: class binding method 3

<div :class="[boolean2 ? 'class3':'class1']"></div>> 
<!-- Ternary operation -->

4.4: style binding method I

<div v-bind:style="{color: colorname , fontSize: fonsize+'px'}"></div>
<!-- use{}definition style Style to get data Values in,{}To follow json format
			{}Do not use in style Property name of the style“ font-size",Use the right one js Property name: border-style-width = borderStyleWidth
-->

4.5: style binding method II

<div v-bind:style="mystyle"></div>
<!-- have access to data Define a style Property string -->

4.6: style binding method III

<div v-bind:style="mystyle2"></div>
<!-- adopt data Object assignment in -->
data:{
  mystyle2:{
    color:"red",
    fontSize:"30px"
  }
}

4.7: style binding method 4

<div v-bind:style="[mystyle , mystyle3]">77777</div>
<!-- Array binding method, you can data Multiple objects bound to style in -->
data:{
  mystyle2:{
    color:"red",
    fontSize:"30px"
  },
  mystyle3:{
    textShadow:"red 3px 3px 3px"
  }
}

5. Condition and list rendering

5.1: v-if and v-sele

In the html tag, you can add a v-if instruction to specify a condition. If the condition is true, the html tag will be displayed. If not, the tag will not be displayed

The condition can be an expression or a boolean value

Tags containing v-if and v-else can only be next to each other

5.2: v-else-if multi branch judgment

<div v-if="code>=90">excellent</div>
<div v-else-if="code>=60">good</div>
<div v-else-if="code<60">fail,</div>
<div v-else>666</div>
<!-- Multi branch statement labels cannot be separated -->

5.3: v-show

In terms of function, v-show and v-if have the same function, and the rendering process is different

v-show is rendered through the style attribute

v-if is true rendering, but it is also lazy rendering

v-if is a "real" conditional rendering because it ensures that the event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during switching.

v-if is also lazy: if the condition is false at the initial rendering, nothing is done -- the conditional block does not start rendering until the condition first becomes true.

In contrast, v-show is much simpler - no matter what the initial conditions are, elements are always rendered and simply switched based on CSS. Generally speaking, v-if has higher switching overhead and v-show has higher initial rendering overhead. Therefore, if you need to switch very frequently, v-show is better; if the conditions change little at run time, It is better to use v-if.

v-show:<div v-show="genderS=='S'">female</div>
v-if:<div v-if="genderM=='M'">male</div>
<input type="text" v-model:value="genderS"> 

6. List rendering

Display the set data on the page in table or list format

6.1: v-for

<tr v-for="s in stus">
  <td>{{s.stuId}}</td>
  <td>{{s.stuName}}</td>
  <td>{{s.stuGender=='M'?'male':'female'}}</td>
  <td>{{s.stuAge}}</td>
</tr>	

7. Event handling: handle user operation events

  • When using vue for data rendering, if you use the native js event binding (such as onclick), if you need to obtain the data in the vue instance and transfer parameters, you need to complete it through splicing

  • vue provides v-on instructions to bind various events (v-on:click), which simplifies the process of obtaining values from vue, but the triggered methods need to be written in the methods code in the instance vue code block

7.1: v-on

<button type="button" v-on:click="deDelete(s.stuAge)">delete</button>
deDelete:function (age){
   console.log("delete"+age)
}
v-on:click --> @click
<button type="button" @click="Update">modify</button>

7.2: using js function to transfer values

<button type="button" v-on:click="deDelete(s.stuAge,s.stuName)">delete</button>
deDelete:function (age,name){
   console.log("delete"+age+name)
}

7.3: use dataset object to transfer value

<button type="button" @click="Update()":data-stuName="s.stuName":data-stuAge="s.stuAge">modify</button>
Update:function (){
       //If the v-on bound js function has no parameters, you can omit (); at the same time, you can give the js function an event parameter (event object) 				          					 // 1.event indicates the event that triggers the current function
       //2. Event.srcalelement indicates the element of the event (Modify button)
       //3. Event.srclelement.dataset represents the dataset on the button (the attribute starting with data)
       var stu = event.srcElement.dataset;
       console.log("update"+stu.stuName+stu.stuAge);
}

7.4: mixed use

  • $EVENT parameter

<button type="button" v-on:click="Event function(General parameters,$event)":data-parameter name="parameter value">delete</button>
<!-- Notes for mixed use event Value transfer needs to be added $event -->
deDelete:function (General parameters,$event){
			 	//Gets the value of the event object dataset
        var stu = event.srcElement.dataset;
        console.log("delete"+age+name+stu.stuimg);
        console.log(event.srcElement.dataset);
}

8. Modifier

When using v-on for event binding, you can add the suffix of the feature and set the feature of event triggering

8.1: use example of event modifier

<form action="www.baidu.com">
		<button type="button" @click.prevent="Event function"></button><!-- Add a modifier back to eliminate the default action of the button -->
</form>

8.2 event modifier:

  • prevent: submit the event, no longer reload the page, and eliminate the default event of the element

  • shop: prevent the event from bubbling (prevent the child tag from bubbling upward to trigger the event of the parent tag)

  • self: prevent the child component from triggering the parent component click event (only the event can be triggered by itself)

  • <div style="height: 200px; width: 200px; background-color: aqua;" @click.self="method1">
       <div style="height: 100px; width: 100px; background-color: fuchsia;" @click.self="method2">
           <button @click.shop="method3">test</button>
       </div>
     </div>
    
  • Once: the event is only triggered once

8.3: key modifier

Key modifiers are modifiers for keyboard events

<input type="text" @keyup.enter="Event function">
<!-- Change the event to press enter Trigger is not triggered by releasing the key -->
  • Limit which key triggers
  • .enter
  • .tab
  • .delete
  • .esc
  • .up
  • .space
  • .down
  • .left
  • .right
  • Keyboard code

8.4: system modifier

Combination key

.ctrl+Keyboard code trigger event
.alt+Keyboard code trigger event
.shift+Keyboard code trigger event
.meta+Keyboard code trigger event

9. Form input binding

Form input binding, that is, two-way binding, is to render the data of vue instance to the form input view (input\textarea\select), and synchronously update the data of input view to the data of vue instance

9.1: bidirectional binding of input box

<input type="text" v-model="Binding element">
data:{
      Binding element:"aaa"
}

9.2: two way binding of radio selection buttons

<!-- Radio button bidirectional binding -->
<input type="radio" v-model="t1" value="A">A 3
<input type="radio" v-model="t1" value="B">B 4
<input type="radio" v-model="t1" value="C">C 5
<input type="radio" v-model="t1" value="D">D 6
 data:{
      t1:"C"//Default selection option C
  }

9.3: check button bidirectional binding

<!-- Check box bidirectional binding -->
<input type="checkbox" v-model="t2" value="Basketball">Basketball<br/>
<input type="checkbox" v-model="t2" value="Football">Football<br/>
<input type="checkbox" v-model="t2" value="Table Tennis">Table Tennis<br/>
<input type="checkbox" v-model="t2" value="badminton">badminton<br/>
 data:{
      t2:[
            "Football","Table Tennis"//These two items are selected by default
      ]
  }

9.4: pull down menu bidirectional binding

<!--  drop-down menu   -->
<select v-model="t3">
    <option value="Beijing">Beijing</option>
    <option value="Shanghai">Shanghai</option>
    <option value="Guangzhou">Guangzhou</option>
    <option value="Shenzhen">Shenzhen</option>
</select>
data:{
      t3:"Shanghai" //Shanghai option is selected by default
}

10.vue use cases

10.1: interface description

Interface name
Request URL
Request modeGET | POST
Request parameterss string [required]
limit int [optional] returns the number of search results. The default value is 10
type int [optional] search type (1 single 10 songs), default 1
offset int [optional] the offset of the search result

11.vue components

Component is to encapsulate common HTML modules - reusable

11.1: component registration

Example:

//Define a new component called button counter
Vue.component('button-counter',{
	data:funtion(){
		return:{
			count : 0
		},
  template:{
          //Html element    
  },
  methods:{
    			//Event function
  }			
        
	}
})
//Define shared code blocks
Vue.component("header-bar",{
  //The data in the component is the object returned by the function
    data:function (){
        return{
            title:"vue In component data"
        }
    },
    template:`
		<table border="1px" style="width:80px;" cellspacing="0">
						{{title}}
        <tr>
            <th>ID</th>
            <th>full name</th>
            <th>Password (encrypted)</th>
            <th>nickname</th>
            <th>name</th>
						<button type="button" @click="test">test</button>
        </tr>
    </table>`,
    methods:{
        test:function (){
            alert("Functions defined in components")
        }
    }
});
//HTML module (HTML tag, CSS style), methods method block and data code block of template component
//You can use the header bar tag in multiple html files to reference the content in the template
//Must be added to the label corresponding to the cause el

11.2: component references

  • Defining a component depends on vue.js. You need to reference vu e.js before referencing the JS file of the custom component
  • The reference of the component must be in the el specified container of the vue instance
<div id="vm">
  <header-bar></header-bar>
</div>

<script type="text/javascript">
  var vm = new Vue({
    el:"#vm"
  })
</script>

11.3: component communication - parent to child

The vue instance itself is a component (the template is the el container, the data container is the component data, and the methods is the component event function) and is the parent component

The component referenced in the el container specified in the vue instance is a child component

Parent to child: when a parent component calls a child component, it passes information to the child component

  • <!-- Parent component reference -->
    <header-bar title="aaa"></header-bar>
    <header-bar :title="str"></header-bar>
    
    <script type="text/javascript">
      var vm = new Vue({
          el:"#vm",
          data:{
              str:"Pass to sub assembly title value"
          }
      })
    </script>
    
    Vue.component("header-bar",{
        //The data in the component is the object returned by the function
        // data:function (){
        //     return{
        //         Title: "data in Vue component"
        //     }
        // },
        template:`
          <div>
          {{title}}
          </div>       
        `,
        props:['title']
    <!-- use props Call the parent component name Corresponding value -->
    });
    
    
    
Father to son
Parent component: data: {STR: "pass to child component title Value"}

Subcomponent: template: < div > {{Title}} < / div >
props: [title] / / receive the name of the value passed from the parent component

11.4: son to father

The function of the parent component is called through the button of the child component, and the value is passed through the function

Son to father
Subcomponent: data:function (){
return{
str: "data in subcomponent"
}
}
< button type = "button" @ click = "chickMethod" > button of subcomponent press button of subcomponent to call function button
methods:{
chickMethod:function (){
this.$emit("my event", this.str) calls the parent component function and passes parameters
}
}
Parent component: < header bar: title = "str" @ my event = "parentMethod" >
methods:{
parentMethod:function (t){
vm.t=t; assign the parameters of the subcomponent to the data
}
}

11.5: component slot

When we customize vue components, we allow some contents in the components to be defined when calling the components – slots

11.5.1: use of slots
  • When customizing a component, the slot is defined in the template of the component through the slot tag
<header-bar :title="str" @my-event="parentMethod">
    <input type="text">	<!-- The customized content is automatically loaded into the slot of the sub component -->
    <button>search</button>
</header-bar>

template:`
	<div>
    <slot></slot>	<!--Custom slot label-->
  </div>`
11.5.2: named slot

If there are two slots in the sub component, you need to define the name in the slot tag

Named slot call
Subcomponents:Parent component:

search
11.5.3: scope of slot

If the parent component needs to use the value in the child component data when defining a slot, it needs to be passed to the parent component in the slot label in the child component

Slot scope
Subcomponents
data:function(){
return:{
str: "data of subcomponent"
s: "Pass to parent component"
}
}
Parent component:



search
{{sc.str}}

12.axios

vue can realize data rendering, but how to obtain data?

vue itself has no communication capability, and is usually used in combination with axios, a js framework focusing on asynchronous communication

  • asios data communication
  • vue data rendering

12.1: getting started with axios

  • Native ajax – implementation steps are complex
  • jquery is bulky
  • axios is concise, efficient and supports Result well

12.1.1: custom request instance of Axios

axios({
    methods: "post",//Request mode
    url:"Request path",
    params:{
        //Set request line
    },
    header:{
        //Set request header
    },
    data:{
        //Set request body (post, put)
    }
}).then(function (rep){
    console.log(rep)
});

12.1.2: asynchronous request instance of Axios

axios.get("Request path").then(function (rep) {
    console.log(rep)
});

12.1.3: concurrent request instance of Axios

 var vm = new Vue({
        el:"#container",
        data:{

        },
        methods:{

        },
        beforeMount:function (){
            //3. After data initialization, you can modify / obtain the value in data before template loading and before data initial rendering (mounting)
            axios.all([queryUser(),queryUserLike()]).then(axios.spread(function (res1,res2){
                console.log(res1)
                console.log(res2)
            }));
        }
    })
function queryUser(){
    return axios.get('http://localhost:8080/FM/user/queryUsers')
}
function queryUserLike(){
    return axios.get('http://localhost:8080/FM/user/queryUserLike/a')
}

12.1.4: arrow function example of Axios

The callback function requested by axios is not the data returned by the interface. You can use this to directly call variables in data

axios.get("http://localhost:8080/FM/user/queryUsers").then((rep)=>{
    console.log(rep)
    this.stu=rep.data.data;
});

13: Route of Vue: router

Router is a plug-in to realize component jump officially provided by vue

13.1: reference of routing plug-in

<script type="text/javascript" src="js/vue-router.js"></script>

13.2: use of routing

<div id="container">
        <ul>
            <li><router-link to="/a">home page</router-link></li><!--Route jump-->
            <li><router-link to="/b">HTML</router-link></li>
            <li><router-link to="/c">JAVA</router-link></li>
            <li><router-link to="/d">PYTHON</router-link></li>
        </ul>
    <div style="width: 100%;height: 200px; background-color: paleturquoise;">
       <router-view></router-view><!--Route template display-->
    </div>
</div>
<script type="text/javascript">
  //Create template
    const t1 = {template: `<p>Template 1 (first page)</p>`};
    const t2 = {template: `<p>Template 2( HTML)</p>`};
    const t3 = {template: `<p>Template 3( JAVA)</p>`};
    const t4 = {template: `<p>Template 4( PYTHON)</p>`};
  
    var router = new VueRouter({
        routes:[{path:"/a",component:t1},
                {path:"/b",component:t2},
                {path:"/c",component:t3},
                {path:"/d",component:t4},]
    });
  
    var vm = new Vue({
        el:"#container",
        router:router//Reference route
    })
</script>

13.3: dynamic route matching

*Can match any route

For example:

  • {path:"/*"}

  • {path: "/ template path - *"}

  • <li><router-link to="/">404</router-link></li>
    <li><router-link to="/user123123123">user-*</router-link></li>
    
    <script type="text/javascript">   
    const t5= {template: `<p>404</p>`};
    routes:[{path:"/*",component:t5},
            {path:"/user-*",component:t5}]//Match paths starting with user -
    </script>
    

    Note: if you use wildcards to define paths, you need to pay attention to the order of route declarations

Priority: if multiple routes are defined for a path, the priority will be higher according to the matching order of routes: the earlier the route is defined, the higher the priority.

13.4: routing parameters

  • /a/id can match paths starting with / a /

<div id="container">
    <router-link to="/a/101">home page</router-link>

    <router-view></router-view>
</div>
<script type="text/javascript">
    const t1 = {template: `<p>Template 1 (first page){{$route.params.id}}</p>`};
    var router = new VueRouter({
        routes:[ {path:"/a/:id",component:t1}]
    });
    var vm = new Vue({
        el:"#container",
        router:router
    })
</script>

13.5: nested routing

When there are one or more router link routes in a route, use children to configure the route and template

example:

<div id="container">
  <router-link to="/a">Template 1</router-link>
  <router-view ></router-view>
</div>
<script type="text/javascript">
  const t1 = {
    template: `<p>
                  <router-link to="/b">In template 1 b Sub template</router-link>
                  <router-link to="/c">In template 1 c Sub template</router-link>
                  <router-view></router-view>
               </p>
                `

  }
  const t2 = {template: `<p>In template 1 b Embedded template
                            <router-link to="/d">b In the sub template d Sub template</router-link>
                            <router-link to="/e">b In the sub template e Sub template</router-link>
                            <router-view></router-view>
                           </p>`}
  const t3 = {template: `<p>In template 1 c Embedded template</p>`}
  const t4 = {template: `<p>Template b Medium d Embedded template</p>`}
  const t5 = {template: `<p>Template b Medium e Embedded template</p>`}
  const myrouter = new VueRouter({
    routes: [{
        path: "/a",
        component: t1,
        children:[{
          path:"/b",
          component:t2,
          children:[{
            path:"/d",
            component:t4
          },
            {
              path:"/e",
              component:t5
            }]
        },{
          path:"/c",
          component:t3
        }]
      }]
  })
  var vm = new Vue({
    el:"#container",
    router:myrouter
  })

</script>

13.6 programming navigation:

<div id="container">
    <router-link to="/a">router-link test</router-link>
    <button type="button" @click="test">Programming navigation test</button>
  <button type="button" @click="back">back off</button>
    <button type="button" @click="forward">forward</button>
    <router-view></router-view>
</div>

<script type="text/javascript">
  const t = {template: `<p>Programming navigation</p>`};
  const myrouter = new VueRouter({
    routes:[{
      path:"/a",
      component:t
    }]
  })

  var vm = new Vue({
    el:"#container",
    router:myrouter,
    methods:{
      test(){
        myrouter.push("/a")
      },
      back:function (){
        myrouter.go(-1)
      },
      forward:function (){
          myrouter.go(1)
      }
    }
  })

Parameter transfer

// character string
router.push('home')

// object
router.push({ path: 'home' })

// Named route
router.push({ name: 'user', params: { userId: '123' }})

// With query parameters, it becomes / register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})


//example
const userId = '123'
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// params here does not take effect
router.push({ path: '/user', params: { userId }}) // -> /user

Step back operation of routing

The go() parameter is an integer, indicating the number of forward / backward steps in the browser history, which is equivalent to the function of window.history.go(-1)

// A step forward in the browser record is equivalent to history.forward()
router.go(1)

// Step back to record, equivalent to history.back()
router.go(-1)

// Record 3 steps forward
router.go(3)

// If the history record is not enough, it will fail silently
router.go(-100)
router.go(100)

13.7: route naming

Named route: when defining a route, you can specify a name for the route. When navigating a route, you can navigate through the name of the route

example:

		
		<input type="text" v-model="name"> //Bidirectional binding
      
    <router-link :to="{name:name}">router-link test</router-link>
    <button type="button" @click="test">Programming navigation test</button>

    const myrouter = new VueRouter({
        routes:[{
          path:"/a",
          name:"/name",//Set the name of the route
          component:t,
        }]
      })
    //Programming call route name
    var vm = new Vue({
      data:{
        name:"/name"
      },
      router:myrouter,
      methods:{
        test:function (){
          myrouter.push({name : vm.name})
        },
      }
  })


13.8: naming of views

When there are multiple views, you need to name the view with name, and configure the route with: components: {}

example:

<router-view name="v1"></router-view>
<router-view name="v2"></router-view>
<script type="text/javascript">
  const t1 = {template: `<p>t1</p>`};
  const t2 = {template: `<p>t2</p>`};
  const t21 = {template: `<p>t21</p>`};
  const t22 = {template: `<p>t22</p>`};
  const myrouter = new VueRouter({
    routes:[{
      path:"/a",
      name:"/aName",
      components: {
          v1:t1, 	//Configure the corresponding view for router view
          v2:t21,
      }
    },{
        path:"/b",
        name:"/bName",
        components: {
            v1:t2,
            v2:t22
        }
    }]
  })

13.9: redirection and alias

  • When the user accesses / a, the URL will be replaced with / B, and then the matching route will be / b
  • Redirection is also done through routes configuration. The following example is redirection from / a to / b

Redirect instance:

routes:[{
    path:"/a",
    redirect:"/b", //It can also be configured by name
    name:"/aName",
    components: {
        v1:t1,
        v2:t21,
    }
  },{
      path:"/b",
      name:"/bName",
      components: {
          v1:t2,
          v2:t22
      }
  }]
})

Alias instance:

<button type="button" @click="test">Alias test</button>

routes:[{
      path:"/a",
      name:"/aName",
      alias:"/cName",//Alias the route
      component:t1
      }]

methods:{
      test:function (){
        myrouter.push('/cName') //Accessing this route will automatically jump to the "/ a" path
      }}

Tags: Javascript Vue.js html

Posted on Sun, 10 Oct 2021 09:35:30 -0400 by Moneypenny