The basic properties of vue and its code examples (take you to learn Vue in ten minutes)

1. Basic application

Case: dynamically bind address to a connection, basic example: dynamic attribute value, more advanced case: click the button to switch link address

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>基本应用</title>
  <script type="text/javascript" src="/js/vue.global.prod.js"></script>
</head>
<body>
  <div id="app">
    <a v-bind:href="link" target="_blank">大力出奇迹</a>
  </div>
</body>
</html>
<script type="text/javascript">
    <!--    声明组合式api-->
    const {
      
      createApp, reactive, toRefs} = Vue
    //  创建一个vue应用
    createApp({
      
      
        //    定义数据,方法等都写在setup函数中
        setup(){
      
      
            //定义的数据
            const data = reactive({
      
      
             link:
             'https://www.baidu.com'
            })
            //定义的数据和方法都需要return返回
            return {
      
      ...toRefs(data)}
        }
    }).mount('#app')
</script>

operation result:
insert image description here
insert image description here

2. Syntactic sugar

Syntactic sugar is the simplified writing method provided by vue. For v-bind, it can be directly: attribute

<a v-bind:href="link" target="_blank">大力出奇迹</a>

3. Binding class class

In practice, there will also be many css classes that use script operations to mark, similar to the .addclass( in jQuery that everyone learned before, there are also class operations in Vue. Case
: single css class bound by v-bind, multiple css classes

4. Binding style style

We can also use v-bind: style to bind some css inline styles
, object form syntax: styler{attribute name: attribute value, attribute
name: attribute value}

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>绑定class类</title>
  <style>
      .xx {
      
      
          width: 100px;
          height: 100px;
          background-color: darkcyan;
      }

      .ww {
      
      
          border-radius: 10px;
      }
  </style>
</head>
<body>
<div id="app">
  <!--   单个css-->
  <div :class="xxclass"></div>
  <div :class="{xx:true}"></div>
  <!--    多个-->
  <div :class="{xx:true,ww:true}"></div>
  <!--    定义成方法-->
  <div :class="classMethodTest()"></div>
</div>
</body>
</html>
<script type="text/javascript" src="/js/vue.global.prod.js"></script>
<script type="text/javascript">
  <!--    声明组合式api-->
  const {
      
      createApp, reactive, toRefs} = Vue
  //  创建一个vue应用
  createApp({
      
      
    //    定义数据,方法等都写在setup函数中
    setup() {
      
      
      //定义的数据
      const data = reactive({
      
      
        xxclass: 'xx',
        wwclass: 'ww'
      })
      const classMethodTest = () =>{
      
      
        return {
      
      xx:true,ww:true}
      }
        //定义的数据和方法都需要return返回
        return {
      
      ...toRefs(data).classMethodTest}
      }
    }).mount('#app')
</script>

5. Computed properties

1. What is a calculated attribute
Calculated attribute: It can be understood as an attribute that can write some calculation logic in it.
Function: 1. Reduce the calculation logic in the template.
2. Data caching. When our data has not changed, the calculation process is no longer performed.
3. Rely on a fixed data type (responsive data), and cannot be a global data that is passed in normally. 2.
Calculated attributes and method
values ​​are not directly rendered to the page, but are also calculated in Suanran to the page after calculation. You can use the calculation Attribute computed
1. The method in methods is called in the template. If this method depends on data and the value of data changes, this method will be re-executed; computed attributes also have this feature. Make sure that the data in data is consistent with the data displayed on the page!
2. The result calculated by the calculated attribute will be cached and displayed directly without calculation next time, but the method is not, and it will be re-executed every time it is called.
3. Modify the value of the computed property
Directly modify the value of the computed property and report an error, Computed property “num2” was assigned to but it has no setter. Define the get and set methods in computed, and modify the value in the computed property 4. Computed
property Configuration
1.get(): Must be written, this function does not accept parameters
2. When is get() called?: When the computed property is read for the first time or the data on which the computed property depends changes, the getter function has a Return value, the return value is the value of the computed property
3.set(): optional, accepts an optional parameter (the value after the computed property is modified)
4. When is set() called?: When the computed property is modified
5. The this that appears in get() and set() is called when it is called to vm

<template>
    <div class="compute">        
        <p>修改计算属性的值</p>
        <h4>num: <span v-text="num"></span></h4>
        <h4>计算属性num2: <span v-text="num2"></span> </h4>
        <button class="btn" @click="change">改变计算属性的值</button>
    </div>
</template>
<script>
export default {
      
      
    name:'compute',
    data(){
      
      
        return{
      
                 
            num:100
        }
    },
    computed:{
      
      
        // num2不是函数
        num2:{
      
      
            // 当计算属性要修改时先触发set方法
            // 读取当前计算属性的值,get方法可以隐藏,默认进入的是get方法
            get:function(){
      
      
                return this.num*2-10
            },
            set:function(val){
      
      
                this.num = val;
                console.log('val',val)
            }
        }
    },
    methods:{
      
             
        change(){
      
      
            // 直接修改计算属性的值报错,Computed property "num2" was assigned to but it has no setter.
            this.num2=60;
        }
    }
}
</script>
<style lang="less" scoped>
.compute{
      
      
    .btn{
      
      
        width: 130px;
        height: 37px;
        background: #fff;
        border-style: none;
        border: 1px solid #333;
        border-radius: 4px;

        &:hover{
      
      
            background: #42c5e6;
            color: #fff;
        }
    }
}
</style>

insert image description here

计算属性
	<!-- <ul>
		<li v-for="item in users.filter(u=>u.gender=='male')">
			{
    
    {item}}
		</li>
	</ul> -->
	
	<button @click="gender='male'">男生</button>
	<button @click="gender='female'">女生</button>
	<ul>
		<li v-for="item in userFilter">
			{
    
    {item}}
		</li>
	</ul>


</div>
<script>
	new Vue({
		el:"#app",
		data:{
			message:"hello world",
			users:[
				{id:1,name:"terry",gender:"male"},
				{id:2,name:"larry",gender:"male"},
				{id:3,name:"vicky",gender:"female"},
				{id:4,name:"lucy",gender:"female"},
				{id:5,name:"tom",gender:"male"},
			],
			//默认值,默认情况显示男生
			gender:"male"
		},
		//computed是一个计算属性,调用里面的方法不用加过好,直接用reverseMessage
		computed:{
			reverseMessage(){
				console.log("computed-reverseMessage"+Math.random())
				return this.message.split("").reverse().join("")
			},
			//过滤
			//u=>u.gender===this.gender  箭头函数
			userFilter(){
			//当this.users以及this.gender发生变化的时候,计算属性会重新执行计算出新的结果然后渲染到页面中。
				return this.users.filter(u=>u.gender===this.gender)
			}
		},
		created(){
			setTimeout(()=>{
				this.message += "hello world"
			},2000)
		},
		methods:{
			reverseMsg(){
				console.log("methods-reverseMsg"+Math.random())
				return this.message.split("").reverse().join("")
			}
		}
	})
</script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>计算属性</title>
  <script type="text/javascript" src="/js/vue.global.prod.js"></script>
</head>
<body>
  <div id="app">
    {
   
   {chineseName.length > 0 ? "有中文名":"没有"}}
  </div>
</body>
</html>
<script type="text/javascript">
    <!--    声明组合式api-->
    const {
      
      createApp, reactive, toRefs} = Vue
    //  创建一个vue应用
    createApp({
      
      
        //    定义数据,方法等都写在setup函数中
        setup(){
      
      
            //定义的数据
            const data = reactive({
      
      
              chineseName:["李小屁","小鬼"]
            })
            //定义的数据和方法都需要return返回
            return {
      
      ...toRefs(data)}
        }
    }).mount('#app')
</script>

Example screenshot:
insert image description here
But if too much logic is written in the template, it will make the template bloated and difficult to maintain, so we can use the computed attribute computed() method to describe complex logic that depends on responsive state

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>计算属性</title>
  <script type="text/javascript" src="/js/vue.global.prod.js"></script>
</head>
<body>
<div id="app">
  {
   
   {c}}
</div>
</body>
</html>
<script type="text/javascript">
  <!--    声明组合式api-->
  const {
      
      createApp, reactive, toRefs,computed} = Vue
  //  创建一个vue应用
  createApp({
      
      
    //    定义数据,方法等都写在setup函数中
    setup() {
      
      
      //定义的数据
      const data = reactive({
      
      
        chineseName: ["李小屁", "小鬼"]
      })
      const c = computed(() =>
        data.chineseName.length > 0 ? '有名字' : '没名字');
        //定义的数据和方法都需要return返回
        return {
      
      ...toRefs(data), c}
      }
    }).mount('#app');
</script>

Example:
insert image description here
So most developers are more familiar with the familiar writing of methods when writing, so what is the difference between writing methods and calculating attributes?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>计算属性</title>
  <script type="text/javascript" src="/js/vue.global.prod.js"></script>
</head>
<body>
<div id="app">
  {
   
   {c}}
  {
   
   {m()}}
</div>
</body>
</html>
<script type="text/javascript">
  <!--    声明组合式api-->
  const {
      
      createApp, reactive, toRefs,computed} = Vue
  //  创建一个vue应用
  createApp({
      
      
    //    定义数据,方法等都写在setup函数中
    setup() {
      
      
      //定义的数据
      const data = reactive({
      
      
        chineseName: ["李小屁", "小鬼"]
      })
      const c = computed(() =>
        data.chineseName.length > 0 ? '有名字' : '没名字');
        //普通方法
      const m = () => {
      
      
        return  data.chineseName.length > 0 ?'有名字':'没名字'
      }
        //定义的数据和方法都需要return返回
        return {
      
      ...toRefs(data), c,m}
      }
    }).mount('#app');
</script>

The difference between computed properties and methods
1, computed properties are essentially methods that contain getters and setters.
When getting a computed property, you are actually calling the getter method of the computed property. Vue will collect the dependencies of the computed property and cache the return result of the computed property. Only when the dependency changes will it recalculate.
2. The method is not cached, and each method call will cause re-execution.
3. The getter and setter parameters of the computed property are fixed, the getter has no parameters, the setter has only one parameter, and the parameters of the method are not limited.
4. Due to the above differences, computed attributes are usually used to obtain other data based on existing data, and it is not recommended to use asynchronous, current time, random number and other side-effect operations in the process of obtaining data.
5. In fact, the most important difference between them is the difference in meaning. A computed attribute is also a data in meaning, which can be read or assigned a value. A method is an operation in meaning to process some things.

6. Use of v-on

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>v-on的使用</title>
</head>
<script type="text/javascript" src="/js/vue.global.prod.js"></script>
<body>
<div id="app">
  <button v-on:click="sub">-</button>
  {
   
   {i}}
  <button v-on:click="add">+</button>
</div>
</body>
</html>
<script type="text/javascript">
  <!--    声明组合式api-->
  const {
      
      createApp, reactive, toRefs, computed} = Vue
  //  创建一个vue应用
  createApp({
      
      
    //    定义数据,方法等都写在setup函数中
    setup() {
      
      
      //定义的数据
      const data = reactive({
      
      
        i:0
      })
      const add = () => {
      
      
        data.i++
      }
      const sub = () => {
      
      
        data.i--
      }
      //定义的数据和方法都需要return返回
      return {
      
      ...toRefs(data),add,sub}
    }
  }).mount('#app')
</script>

Example:
insert image description here

7. Parameter passing

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>参数传递</title>
</head>
<script type="text/javascript" src="/js/vue.global.prod.js"></script>
<body>
<div id="app">
  <button v-on:click="sub(10)">-</button>
  {
   
   {i}}
  <button v-on:click="add(10,$event)">+</button>
</div>
</body>
</html>
<script type="text/javascript">
  <!--    声明组合式api-->
  const {
      
      createApp, reactive, toRefs, computed} = Vue
  //  创建一个vue应用
  createApp({
      
      
    //    定义数据,方法等都写在setup函数中
    setup() {
      
      
      //定义的数据
      const data = reactive({
      
      
        i:0
      })
      const add = (num,e) => {
      
      
        console.log(e)
        data.i += num
      }
      const sub = (num) => {
      
      
        data.i -= num
      }
      //定义的数据和方法都需要return返回
      return {
      
      ...toRefs(data),add,sub}
    }
  }).mount('#app')
</script>

Example:
insert image description here

8. The use of v-if

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>v-if的使用</title>
</head>
<script type="text/javascript" src="/js/vue.global.prod.js"></script>
<body>
<div id="app">
  <div>
    <h2 v-if="score>90">优秀</h2>
    <h2 v-else-if="score>70">及格</h2>
    <h2 v-else>不及格</h2>
  </div>
</div>
</body>
</html>
<script type="text/javascript">
  <!--    声明组合式api-->
  const {
      
      createApp, reactive, toRefs, computed} = Vue
  //  创建一个vue应用
  createApp({
      
      
    //    定义数据,方法等都写在setup函数中
    setup() {
      
      
      //定义的数据
      const data = reactive({
      
      
        score: 91
      })
      //定义的数据和方法都需要return返回
      return {
      
      ...toRefs(data)}
    }
  }).mount('#app')
</script>

Example:
insert image description here

10.v-show

v-show also has the function of judging, but v-if is a real judgment. If the condition fails, the label will not be displayed during rendering. v-show judges whether to display it through the style. If the judgment fails, will add css display:none to the label

<h2 v-show="score>80">{
   
   {message}}</h2> 

11. Use of v-for

traverse objects

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>v-if的使用</title>
</head>
<script type="text/javascript" src="/js/vue.global.prod.js"></script>
<body>
<div id="app">
<!--  普通获取-->
  <span>{
   
   {student.name}}</span>
<!--  循环-->
  <span v-for="(item,key) in student">{
   
   {key}}-{
   
   {item}}</span><br>
</div>
</body>
</html>
<script type="text/javascript">
  <!--    声明组合式api-->
  const {
      
      createApp, reactive, toRefs, computed} = Vue
  //  创建一个vue应用
  createApp({
      
      
    //    定义数据,方法等都写在setup函数中
    setup() {
      
      
      //定义的数据
      const data = reactive({
      
      
        student:{
      
      
          name:'张三',
          age: 23,
          hobbies:'抽烟喝酒烫头'
        }
      })
      //定义的数据和方法都需要return返回
      return {
      
      ...toRefs(data)}
    }
  }).mount('#app')
</script>

Example:
insert image description here

traverse objects

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>v-for遍历数组</title>
</head>
<script type="text/javascript" src="/js/vue.global.prod.js"></script>
<body>
<div id="app">
<!--  循环-->
  <span v-for="(item,key) in student">{
   
   {key}}-{
   
   {item}}</span><br>
</div>
</body>
</html>
<script type="text/javascript">
  <!--    声明组合式api-->
  const {
      
      createApp, reactive, toRefs, computed} = Vue
  //  创建一个vue应用
  createApp({
      
      
    //    定义数据,方法等都写在setup函数中
    setup() {
      
      
      //定义的数据
      const data = reactive({
      
      
        student:['jack','tom','李小屁']
      })
      //定义的数据和方法都需要return返回
      return {
      
      ...toRefs(data)}
    }
  }).mount('#app')
</script>

Example:
insert image description here

12 v-bind example

The role of v-bind is to bind data and element attributes.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>v-bind示例</title>
  <style>
      .checkDiv {
      
      
          width: 50px;
          height: 50px;
          border-radius: 50px;
          background-color: aqua;
      }
  </style>
</head>
<script type="text/javascript" src="/js/vue.global.js"></script>
<body>
<div id="app">
<div class="checkDiv" v-bind:style="{width:w+'px',height:h+'px'}" v-on:click="checkDiv()"></div>
</div>
</body>
</html>
<script>
  <!--    声明组合式api-->
  const {
      
      createApp, reactive, toRefs} = Vue
  //  创建一个vue应用
  createApp({
      
      
    //    定义数据,方法等都写在setup函数中
    setup() {
      
      
      //定义的数据
      const data = reactive({
      
      
        w: 50,
        h: 50
      })
      //方法
      const checkDiv = () => {
      
      
        data.w += 10,
        data.h += 10
      }

      const getStyle = () => {
      
      
          return{
      
      width:data.w+'px',height:data.h+'px'}
      }
      //定义的数据和方法都需要return返回
      return {
      
      ...toRefs(data),checkDiv,getStyle}
    }
  }).mount('#app')
</script>

Note:
v-bind is followed by: attribute name=, my understanding is to bind this attribute. After binding, the corresponding value should be found in the data of vue. Of course, it can also be equal to a constant, so that there is no need to go to the data. found.
When we change the url in the console, the corresponding will also change.
Similarly, we can also bind the image src attribute and the class of the hyperlink

var app = new Vue({
    el:'.app',
    data:{
        url:"https://www.baidu.com",
        imgsrc:"https://cn.vuejs.org/images/logo.png",
        class:"btn btn-default"
    }
});
<div class="app">
    <a v-bind:href="url" v-bind:class="klass">click me</a>
    <img v-bind:src="imgsrc">
</div>  

13 single button radio

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>radio</title>
</head>
<script type="text/javascript" src="/js/vue.global.js"></script>
<body>
<div id="app">
<!--    男<input name="sex" type="radio" value="男" checked="sex=='男">-->
<!--    女<input name="sex" type="radio" value="女" checked="sex=='女">-->

<!--    男<input name="sex" type="radio" value="男" v-model="sex">-->
<!--    女<input name="sex" type="radio" value="女" v-model="sex">--><input name="sex" type="radio" value="0" v-model="sex"><input name="sex" type="radio" value="1" v-model="sex">
</div>
</body>
</html>
<script>
<!--    声明组合式api-->
   const {
      
      createApp, reactive, toRefs} = Vue
  //  创建一个vue应用
  createApp({
      
      
   //    定义数据,方法等都写在setup函数中
       setup(){
      
      
           //定义的数据
           const data = reactive({
      
      
               sex:1
           })
           //定义的数据和方法都需要return返回
           return {
      
      ...toRefs(data)}
       }
   }).mount('#app')
</script>

14 checkbox styles

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script type="text/javascript" src="/js/vue.global.js"></script>
<body>
<div id="app">
<!--    单选框-->
    <lable for="argee">
        <input type="checkbox" id="agree" v-model="isAgree">同意协议
    </lable>
    <button :disabled="!isAgree">下一步</button>
    <br>
<!--    复选框-->
    <input name="hobbies" type="checkbox" value="抽烟" v-model="hobbies">抽烟
    <input name="hobbies" type="checkbox" value="喝酒" v-model="hobbies">喝酒
    <input name="hobbies" type="checkbox" value="烫头" v-model="hobbies">烫头
</div>
</body>
</html>
<script>
<!--    声明组合式api-->
   const {
      
      createApp, reactive, toRefs} = Vue
  //  创建一个vue应用
  createApp({
      
      
   //    定义数据,方法等都写在setup函数中
       setup(){
      
      
           //定义的数据
           const data = reactive({
      
      
               isAgree : false,
               hobbies: ['抽烟','烫头']
           })
           //定义的数据和方法都需要return返回
           return {
      
      ...toRefs(data)}
       }
   }).mount('#app')
</script>

15 drop down list

Dropdown list: select tag

Usage scenario: On a page, if there are multiple options for users to choose, using the drop-down list defined by the select tag can effectively save space.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script type="text/javascript" src="/js/vue.global.js"></script>
<body>
<div id="app">
    <select name="f" v-model="fruit" multiple="multiple">
        <option value="苹果">苹果</option>
        <option value="哈密瓜">哈密瓜</option>
        <option value="草莓">草莓</option>
        <option value="车厘子">车厘子</option>
        <option value="榴莲">榴莲</option>
    </select>
</div>
</body>
</html>
<script>
<!--    声明组合式api-->
   const {
      
      createApp, reactive, toRefs} = Vue
  //  创建一个vue应用
  createApp({
      
      
   //    定义数据,方法等都写在setup函数中
       setup(){
      
      
           //定义的数据
           const data = reactive({
      
      
              fruit:['车厘子']
           })
           //定义的数据和方法都需要return返回
           return {
      
      ...toRefs(data)}
       }
   }).mount('#app')
</script>

Example:insert image description here

16 Multi-select drop-down list

1. Multiple selection drop-down list
1. Framework: ?
2. multiple="multiple" is used to: support multiple selections
size is used to: set the number of items

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script type="text/javascript" src="/js/vue.global.js"></script>
<body>
<div id="app">
   <span v-for="(item,index) in allFruits">
       {
   
   {item}}<input type="checkbox" :value="item" v-model="selectFruit">
   </span>
</div>
</body>
</html>
<script>
<!--    声明组合式api-->
   const {
      
      createApp, reactive, toRefs} = Vue
  //  创建一个vue应用
  createApp({
      
      
   //    定义数据,方法等都写在setup函数中
       setup(){
      
      
           //定义的数据
           const data = reactive({
      
      
                allFruits:['香蕉','车厘子','榴莲','芒果','黄桃','荔枝'],
               selectFruit:['榴莲','车厘子']
           })
           //定义的数据和方法都需要return返回
           return {
      
      ...toRefs(data)}
       }
   }).mount('#app')
</script>

Example:
insert image description here
Controls

1. file control: dedicated to file upload
2. hidden control: hidden field, invisible on the web page, but the data will be automatically submitted to the server when the form is submitted
3. readonly and disabled:
(1) Similarities: both are only Read can not be modified
(2) Differences: readonly data can be submitted to the server, disabled data will not be submitted, even if there is a name attribute, it will not be submitted
4. The maxlength of the input control: set the number of characters that can be entered in the text box

Guess you like

Origin blog.csdn.net/weixin_52859229/article/details/130091532