Shang Silicon Valley_Front-end Technology_Vue Family Bucket

Vue technology stack (FamilyBucket)

Shang Silicon Valley Front-end Research Institute

Chapter 1: Vue Core

1.1Vue Introduction

1. Official website

  1. English official website: https://vuejs.org/
  2. Chinese official website: https://cn.vuejs.org/

2. Introduction and description

  • A **Progressive** JavaScript framework for dynamically building user interfaces
  • Author: You Yuxi

3. Features of Vue

  • Follow the **MVVM** pattern
  • Simple coding, small size, high operating efficiency, suitable for mobile/PC development
  • It only focuses on the UI, and can also introduce other third-party library development projects

4. Association with other JS frameworks

  • Learn from Angular’s ​​template and data binding technology
  • Learn from React’s componentization and **virtual DOM** technology

5. Vue peripheral library

  • vue-cli: vue leg rest
  • vue-resource
  • axios
  • vue-router: routing
  • vuex: state management
  • element-ui: UI component library based on vue (PC side)…

1.2 First Learning Vue

  1. If you want Vue to work, you must create a Vue instance and pass in a configuration object;
  2. The code in the root container still conforms to the HTML specification, but some special Vue syntax is mixed in;
  3. The code in the root container is called [Vue template];
  4. There is a one-to-one correspondence between Vue instances and containers;
  5. In real development, there is only one Vue instance, and it will be used together with components;
  6. { {xxx}}xxx in should be written as js expression, and xxx can automatically read all attributes in data;
  7. Once the data in data changes, the places where the data is used in the page will be automatically updated;

Note the distinction: js expressions and js codes (statements)
1. Expression: An expression will produce a value and can be placed anywhere a value is required:
(1). a
(2). a+b
(3) . demo(1)
(4). x === y ? 'a' : 'b'
2.js code (statement)
(1). if(){}
(2). for(){}

<body>
	<!-- 准备好一个容器 -->
	<div id="demo">
		<h1>Hello,{
   
    
    {
   
    
    name.toUpperCase()}}</h1>
	</div>

	<script type="text/javascript" >
		Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。

		//创建Vue实例
		new Vue({
   
    
    
      
      //el用于指定当前Vue实例为哪个容器服务,值通常为css选择器字符串。
			el:'#demo', 
      
      //data中用于存储数据,数据供el所指定的容器去使用,值我们暂时先写成一个对象。
			data:{
   
    
     
				name:'atguigu',
				address:'北京'
			}
		})
	</script>
</body>

1.3 Template syntax

1. Understanding of templates

HTML contains some JS syntax codes. The syntax is divided into two types, namely:

  • Interpolation syntax (double brace expression){ { }}
  • Instructions (starting with v-)

2. Interpolation syntax

  • Function: Used to parse tag body content
  • Syntax: { {xxx}}, xxxx will be parsed as a js expression, and all attributes in the data can be read directly.

3. Command syntax

  • Function: Parse tag attributes, parse tag body content, bind events...
  • For example: v-bind:href = 'xxxx'or abbreviated as :href="xxx"xxxx will be parsed as a js expression, and all attributes in the data can be read directly.
  • Note: There are many instructions in Vue. Here I just use v-bind as an example.
<body>
    <div class="root">
        <h1>插值语法</h1>
        <h2>你好,{
   
    
    {
   
    
    name}}</h2>
        <hr>
        <h1>指令语法</h1>
        <a v-bind:href="school.url" v-bind:x="hello">点我去{
   
    
    {
   
    
    school.name}}学习</a>
        <!-- v-bind: 简写 : -->
        <a :href="school.url" :x="hello">点我去尚硅谷学习</a>
    </div>
    <script>
        Vue.config.productionTip = false
        const x = new Vue({
   
    
    
            el:'.root',
            data:{
   
    
    
                name:"vue",
                school:{
   
    
    
                    name: "尚硅谷",
                    url: "http://www.atguigu.com"
                },
                hello:"hi"
            }
        })
    </script>
</body>

4. Two ways of writing el and data

1. There are two ways to write el
(1). Configure the el attribute when new Vue.
(2). First create a Vue instance, and then specify the value of el through vm.$mount('#root').
2. There are two ways to write data
(1). Object style
(2). Functional style.
How to choose: Any writing method is acceptable at present. When learning components in the future, data must use functional style, otherwise an error will be reported.
3. An important principle:
functions managed by Vue must not write arrow functions. Once an arrow function is written, this is no longer a Vue instance, but a window.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>el与data的两种写法</title>
		<!-- 引入Vue -->
		<script type="text/javascript" src="../js/vue.js"></script>
	</head>
	<body>
		<!-- 准备好一个容器-->
		<div id="root">
			<h1>你好,{
  
   
   {name}}</h1>
		</div>
	</body>

	<script type="text/javascript">
		Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。

		//el的两种写法
		/* const v = new Vue({
			//el:'#root', //第一种写法
			data:{
				name:'尚硅谷'
			}
		})
		console.log(v)
    setTimeout(function(){
       X.$mount(".root")  //第二种写法
    },2000) */

		//data的两种写法
		new Vue({
     
      
      
			el:'#root',
      
			//data的第一种写法:对象式
			/* data:{
				name:'尚硅谷'
			} */

			//data的第二种写法:函数式
			data(){
     
      
      
				console.log('@@@',this) //此处的this是Vue实例对象
				return{
     
      
      
					name:'尚硅谷'
				}
			}
		})
	</script>
</html>

1.4 Data binding

1. One-way data binding

  1. Syntax: v-bind:href ="xxx"or abbreviated as :href
  2. Features: Data can only flow from data to page

2. Two-way data binding

  1. Syntax: v-mode:value="xxx"or abbreviated asv-model="xxx"
  2. Features: Data can not only flow from data to page, but also from page to data.

Remark:

  1. Two-way binding is generally applied to form elements (such as input, select, etc.)
  2. v-model:valueIt can be abbreviated as v-model, because v-modelthe value is collected by default .
<body>
  <div id="root">
    
    单向数据绑定:<input type="text" v-bind:value="name">
    <br>
    双向数据绑定:<input type="text" v-model:value="name">
    
    <!-- 简写 -->
    单向数据绑定:<input type="text" :value="name"><br/>
    双向数据绑定:<input type="text" v-model="name"><br/>
    
    <!-- 如下代码是错误的,因为v-model只能应用在表单类元素(输入类元素)上 -->
    <!-- <h2 v-model:x="name">你好啊</h2> -->
  </div>
  <script>
    new Vue({
     
      
      
      el: "#root",
      data: {
     
      
      
        name: "尚硅谷"
      }
    })
  </script>
</body>

1.5 MVVM model

  1. M: Model: corresponds to the data in data
  2. V: View: template code
  3. VM: ViewModel: Vue instance object

  • All attributes in data finally appear on vm.
  • All attributes on vm and all attributes on the vue prototype can be used directly in the Vue template.

2.png

1.6 Data Agent

1. Object.defineProperty

Object.defineProperty()The method directly defines a new property on an object, or modifies an existing property of an object, and returns the object.
Syntax: Object.defineProperty(obj,prop,descriptor)
Parameters:

  • obj: The object on which the properties are to be defined.
  • prop: The name of the property to be defined or modified.
  • descriptor: the attribute descriptor to be defined or modified.

Setting items

  • value: attribute value
  • enumerable:trueControls whether the property can be enumerated. The default value is false.
  • writable:trueControls whether the property can be modified. The default value is false.
  • configurable:trueControls whether the attribute can be deleted. The default value is false.
let number = 35
let person ={
   
    
    
  name:"孙悟空",
  gender:"男"
}

//通过该方法添加的属性,默认不可枚举,修改,删除
Object.defineProperty(person,"age",{
   
    
    
  // value:45,
  // enumerable:true,  //控制属性是否可以枚举,默认值是 false
  // writable:true,  //控制属性是否可以被修改,默认值是 false
  // configurable:true,  //控制属性是否可以被删除,默认值是 false
  
  //有人读取person 的age 属性时,get函数(getter)就会被调用,且返回值就是age的值
  //现用现取,如果number 的值改变 ,age 属性是改变后的值
  get(){
   
    
    
    console.log("有人读取了age属性")
    return number
  },
  //有人修改person 的age 属性时,set函数(setter)就会被调用,且会收到修改的具体值
  set(value){
   
    
    
    console.log("有人修改了age属性")
    number = value 
  }
})
console.log(person)
console.log(Object.keys(person))

2. What is a data broker?

Operations (read/write) on properties in another object through an object proxy

let obj = {
   
    
    X : 100}
let obj2 = {
   
    
    Y :200}
Object.defineProperty(obj2,"X",{
   
    
    

  get(){
   
    
    
    //将obj 的 X 值设置到 obj2 的X值上
    return obj.X
  },
  set(value){
   
    
    
    //使obj的X值等于,修改后的obj2的 X 值 
    obj.X=value
  }
})

console.log(obj2.X) //100
obj2.X = 300
console.log(obj.X) //300

3. Data proxy in vue

1. Data proxy in Vue: proxy
the operation (read/write) of attributes in the data object through the vm object
2. Benefits of the data proxy in Vue:
more convenient operation of data in data
3. Basic principle:
through Object.defineProperty () Add all attributes in the data object to the vm.
For each property added to the vm, specify a getter/setter.
Operate (read/write) the corresponding attributes in data inside the getter/setter.

2.png

1.7 Event handling

1. Bind monitoring

<div id="root">
  <h2>欢迎来到{
   
    
    {
   
    
    name}}学习</h2>
  <!-- <button v-on:click="showInfo">点我提示信息</button> -->
  <button @click="showInfo1">点我提示信息1(不传参)</button>
  <button @click="showInfo2($event,66)">点我提示信息2(传参)</button>
</div>
</body>

<script type="text/javascript">
  Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
  const vm = new Vue({
   
    
    
    el:'#root',
    data:{
   
    
    
      name:'尚硅谷',
    },
    methods:{
   
    
    
      showInfo1(event){
   
    
    
        // console.log(event.target.innerText)
        // console.log(this) //此处的this是vm
        alert('同学你好!')
      },
      showInfo2(event,number){
   
    
    
        console.log(event,number)
        // console.log(event.target.innerText)
        // console.log(this) //此处的this是vm
        alert('同学你好!!')
      }
    }
  })
</script>


2. Event modifiers

  • .prevent: The default behavior of preventing events event.preventDefault() (commonly used)
  • .stop: Stop event bubbling event.stopPropagation() (commonly used)
  • .once: The event is only triggered once (commonly used);
  • .capture:Use event capture mode;
  • .self: The event is only triggered when event.target is the element of the current operation;
  • .passive: The default behavior of the event is executed immediately, without waiting for the event callback to complete;
  <div id="root">
    <h2>欢迎来到{
  
   
   {name}}学习</h2>
    <!-- 阻止默认事件(常用) -->
    <a href="http://www.atguigu.com" @click.prevent="showInfo">点我提示信息</a>
    
    <!-- 阻止事件冒泡(常用) -->
    <div class="demo1" @click="showInfo">
      <button @click.stop="showInfo">点我提示信息</button>
      
      <!-- 修饰符可以连续写 -->
      <!-- <a href="http://www.atguigu.com" @click.prevent.stop="showInfo">点我提示信息</a> -->
    </div>
    
    <!-- 事件只触发一次(常用) -->
    <button @click.once="showInfo">点我提示信息</button>
    
    <!-- 使用事件的捕获模式 -->
    <div class="box1" @click.capture="showMsg(1)">
      div1
      <div class="box2" @click="showMsg(2)">
        div2
      </div>
    </div>
    
    <!-- 只有event.target是当前操作的元素时才触发事件; -->
    <div class="demo1" @click.self="showInfo">
      <button @click="showInfo">点我提示信息</button>
    </div>
    
    <!-- 事件的默认行为立即执行,无需等待事件回调执行完毕; -->
    <ul @wheel.passive="demo" class="list">
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
    </ul>
  </div>
</body>

3. Key modifier

  • keycode: the key that operates on a certain keycode value
  • keyName: the key of a certain key name of the operation (a small part)
  1. Commonly used button aliases in Vue:
  • Enter => enter
  • Delete => delete (captures "delete" and "backspace" keys)
  • exit => esc
  • Space => space
  • Line break => tab (special, must be used with keydown)
  • up => up
  • down => down
  • left => left
  • right => right
  1. Vue does not provide aliased keys. You can use the original key value of the key to bind it, but be sure to convert it to kebab-case (dash naming).

  2. System modifier keys (special usage): ctrl, alt, shift, meta

    (1). Use with keyup: While pressing the modifier key, press other keys, and then release other keys, the event will be triggered.
    (2). Used with keydown: trigger events normally.

  3. You can also use keyCode to specify specific keys (not recommended)

  4. Vue.config.keyCodes.自定义键名 = 键码, you can customize button aliases

<div id="root">
  <h2>欢迎来到{
  
   
   {name}}学习</h2>
  <input type="text" placeholder="按下回车提示输入" @keydown.enter="showInfo">
</div>

1.8 Computed properties and monitoring

1.Computed property-computed

  1. Definition: The attribute to be used does not exist and must be calculated from existing attributes.

  2. Principle: The bottom layer uses the getters and setters provided by the Objcet.defineproperty method.

  3. Computed properties are defined in computed objects.

  4. Use { {method name}} in the page to display the calculated results.

  5. When will the get function be executed?

    1). It will be executed once when reading for the first time.
    2). It will be called again when the dependent data changes.

  6. Advantages: Compared with methods implementation, there is an internal caching mechanism (reuse), which is more efficient and easy to debug.

  7. Remark:

    1). The calculated attributes will eventually appear on the vm and can be read and used directly.
    2). If the calculated attribute is to be modified, a set function must be written to respond to the modification, and the set must cause the data relied upon for calculation to change.

	<body>
		<div id="root">
			姓:<input type="text" v-model="firstName"> <br/><br/>
			名:<input type="text" v-model="lastName"> <br/><br/>
			全名:<span>{
  
   
   {fullName}}</span> <br/><br/>
		</div>
	</body>
	<script type="text/javascript">
		const vm = new Vue({
     
      
      
			el:'#root',
			data:{
     
      
      
				firstName:'迪丽',
				lastName:'热巴',
			},
			computed:{
     
      
      
				fullName:{
     
      
      
					//get有什么作用?当有人读取fullName时,get就会被调用,且返回值就作为fullName的值
					//get什么时候调用?1.初次读取fullName时。2.所依赖的数据发生变化时。
					get(){
     
      
      
						console.log('get被调用了')
						// console.log(this) //此处的this是vm
						return this.firstName + '-' + this.lastName
					},
					//set什么时候调用? 当fullName被修改时。
					set(value){
     
      
      
						console.log('set',value)
						const arr = value.split('-')  //将接收的值以 '-'拆分为数组
						this.firstName = arr[0]
						this.lastName = arr[1]
					}
				}
			}
		})
	</script>

Abbreviation (you can only write it this way when you only need to read it and do not need to modify it)

<script>
  let vm = new Vue({
   
    
    
    el:"#root",
    data:{
   
    
    
      firstName:"迪丽",
      lastName:"热巴"
    },
    computed:{
   
    
    
      fullName(){
   
    
    
        return this.firstName +'-'+ this.lastName
      }
    }
  })
</script>

2. Monitoring attributes-watch

  • Monitor specified properties by configuring the vm object's $watch()orwatch
  • When the property changes, the callback function is automatically called and calculation is performed inside the function.
  • immediate:trueLet the handler call it during initialization
body>
    <div id="root">
        <h1>今天天气很{
   
    
    {
   
    
    info}}</h1>
        <button @click="changeWeather">点击切换天气</button>
    </div>
    <script>
        const vm = new Vue({
   
    
    
            el:"#root",
            data:{
   
    
    
                isHot:true
            },
            computed:{
   
    
    
                info(){
   
    
    
                    return this.isHot? '炎热' :'寒冷'
                }
            },
            methods:{
   
    
    
                changeWeather(){
   
    
    
                    this.isHot =!this.isHot
                }
            },
            // 监视属性 写法一
            watch:{
   
    
    
                isHot:{
   
    
    
                    immediate:true, //初始化时让 handler 调用一下
                    // 当 isHot 发生改变时调用
                    handler(newValue,oldValue){
   
    
    
                        console.log("isHot被修改了", newValue,oldValue); // true false
                    }
                },
                info: {
   
    
    
                    // immediate: true, 
                    // 当 info 发生改变时调用
                    handler(newValue, oldValue) {
   
    
    
                        console.log("info被修改了", newValue, oldValue); // 炎热 寒冷
                    }
                } 
            }
        })

        // 监视属性 写法二
        // vm.$watch('isHot',{
   
    
    
        //     immediate: true, //初始化时让 handler 调用一下
        //     // 当 isHot 发生改变时调用
        //     handler(newValue, oldValue) {
   
    
    
        //         console.log("isHot被修改了", newValue, oldValue); // true false
        //     }
        // })
    </script>
</body>

1) Deep monitoring deep:true
(1).Vue中的watch默认不监测对象内部值的改变(一层)。<br />   
(2).配置`deep:true`可以监测对象内部值改变(多层)。<br />

备注:<br />   
(1).Vue自身可以监测对象内部值的改变,但Vue提供的watch默认不可以!<br />    
(2).使用watch时根据数据的具体结构,决定是否采用深度监视。
<body>
    <div id="root">
        <h1>a : {
   
    
    {
   
    
    numbers.a}}</h1>
        <button @click="numbers.a++">点击a的值 + 1</button>
    </div>
    <script>
        const vm = new Vue({
   
    
    
            el:"#root",
            data:{
   
    
    
                numbers:{
   
    
    
                    a:1,
                    b:2
                }
            },
            watch:{
   
    
    
                //监视多级结构中某个属性的变化
                // "numbers.a":{
   
    
    
                //     handler(){
   
    
    
                //         console.log("a被改变了");
                //     }
                // }

                //监视多级结构中所有属性的变化
                numbers:{
   
    
    
                    deep:true, //开启深度监视
                    handler(){
   
    
    
                        console.log("numbers 被改变了");
                    }
                }
            }
        })
    </script>
</body>

2) Monitor abbreviation attributes

The abbreviation can be used only when the following configuration is not required.
immediate: trueLet the handler call
deep:trueDeep Monitoring during initialization.

Syntax:
watch:{ 要监视属性(){} }
vm.$watch( '要监视属性',function(){} )(You cannot use arrow functions, which will change the value of this)

const vm = new Vue({
   
    
    
  el:"#root",
  data:{
   
    
    
    numbers:{
   
    
    
      a:1,
      b:2
    }
  },
  //写法1 简写
  watch:{
   
    
    
    "numbers.a"(newValue,oldValue){
   
    
    
      console.log("a被改变了");
    }
  }
})

//写法2 简写
vm.$watch("numbers.a",function(newValue, oldValue){
   
    
    
  console.log("a被改变了", newValue, oldValue)
})

3) watch vs computed

The difference between computed and watch:
1. Watch can complete all the functions that computed can complete.
2. The functions that watch can complete may not be completed by computed. For example, watch can perform asynchronous operations.
Two important principles:
1. All functions managed by Vue are best written as ordinary functions, so that this points to the vm or component instance object.
2. All functions that are not managed by Vue (timer callback functions, ajax callback functions, etc., Promise callback functions) are best written as arrow functions, so that this points to the vm or component instance object.

3.png

<div id="root">
  : <input type="text" v-model="firstName"> <br><br>
  : <input type="text" v-model="lastName"> <br><br>
  全名 : <h1>{
   
    
    {
   
    
    fullName}}</h1>
</div>
<script>
  Vue.config.productionTip = false
 const vm = new Vue({
   
    
    
  el:"#root",
  data:{
   
    
    
    firstName:"迪丽",
    lastName:"热巴",
    fullName:"迪丽-热巴"
  },
  // 计算属性 (不能开启异步任务计算属性)
  // computed:{
   
    
    
  //     fullName(){
   
    
    
  //         return this.firstName +'-'+ this.lastName
  //     }
  // },

  // 监视属性 (可以开启异步任务)
  watch:{
   
    
    
    firstName(value){
   
    
    
      setTimeout(()=>{
   
    
    
        this.fullName = value + '-' + this.lastName
      },1000)
    },
    lastName(value){
   
    
    
      this.fullName = this.firstName +'-'+value
    }
  }
})
</script>

1.9 class and style binding

1. Understand

  • In the application interface, the style of certain element(s) changes
  • Class/style binding is a technology specifically used to achieve dynamic style effects.

2. class style binding

  • :class='xxx'xxx can be a string, object, array

  • The expression is a string: 'classA'

The string writing method is suitable for: the class name is uncertain and needs to be obtained dynamically.

    <style>
        .basic{
   
    
    
            width: 200px;
            height: 100px;
        }
        .normal{
   
    
    
            background-color: aquamarine;
        }
        .happy{
   
    
    
            background-color: red;
        }
        .sad{
   
    
    
            background-color: #f0f0ff;
        }
    </style>

<body>
    <div id="root">
        <div class="basic" :class="mood" @click="changeMood">{
   
    
    {
   
    
    name}}</div>
    </div>  
</body>
<script>
    Vue.config.productionTip = false
    const vm = new Vue({
   
    
    
        el: "#root",
        data: {
   
    
    
            name: "迪丽热巴",
            mood: "normal"
        },
        methods: {
   
    
    
            changeMood() {
   
    
    
                const arr = ["happy", "sad", "normal"]
                this.mood = arr[Math.floor(Math.random() * 3)]
            }
        }
    })
</script>
  • Expressions are objects:{classA:isA, classB: isB}

Applicable to: The number of styles to be bound is determined, and the names are also determined, but it needs to be dynamically decided whether to use it or not.

<body>
    <div id="root">
        <div class="basic" :class="classObj" @click="changeMood">{
   
    
    {
   
    
    name}}</div>
    </div>  
</body>
<script>
    Vue.config.productionTip = false
    const vm = new Vue({
   
    
    
        el: "#root",
        data: {
   
    
    
            name: "迪丽热巴",
            classObj:{
   
    
    
                sad: false,
                red: false
            }
        },
        methods: {
   
    
    
            changeMood(){
   
    
    
                this.classObj.sad = !this.classObj.sad
            }
        },
    })
</script>
  • The expression is an array: ['classA', 'classB']

Applicable to: The number of styles to be bound is uncertain, and the names are also uncertain.

<body>
    <div id="root">
        <div class="basic" :class="classArr" @click="changeMood">{
   
    
    {
   
    
    name}}</div>
    </div>  
</body>
<script>
    Vue.config.productionTip = false
    const vm = new Vue({
   
    
    
        el: "#root",
        data: {
   
    
    
            name: "迪丽热巴",
            classArr:["normal","happy","sad"],
        },
        methods: {
   
    
    
            changeMood(){
   
    
    
                this.classArr.push("red")
            }
        },
    })
</script>

3. style style binding

  • :style="{ color: activeColor, fontSize: fontSize + 'px' }"

where activeColor/fontSize is the data attribute

  • :style="{fontSize: xxx}"where xxx is a dynamic value.
  • :style="[a,b]"Among them, a and b are style objects.
<body>
    <div id="root">
        //对象写法
        <div class="basic" :style

Guess you like

Origin blog.csdn.net/weixin_44359444/article/details/126907875