Vue day01

Vue

1 Introduction:

Vue is a progressive framework for building user interfaces . Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up. Vue's core library only focuses on the view layer, which is not only easy to use, but also easy to integrate with third-party libraries or existing projects. On the other hand, when combined with a modern toolchain and various supporting libraries, Vue is also fully capable of powering complex single-page applications. It is used for single-page application-index.html, and the vue plug-in routing for page jumps to achieve jumps.

【vue】https://cn.vuejs.org/

[Gitee cover character: You Yuxi talks about Vue.js] https://gitee.com/gitee-stars/14

[Interview with Vue author You Yuxi] https://www.jianshu.com/p/3092b382ee80

[Object.defineProperty() detailed explanation expands understanding of vue source code] https://www.cnblogs.com/ldq678/p/13854113.html https://zhuanlan.zhihu.com/p/22695144

1-Vue基本渲染-插值
### js代码
    window.onload = function () {
    
    
            // 创建vue实例,vue实例要与模板(DOM)绑定
           let vm= new Vue({
    
    
                el: "#app",
                data: {
    
    // 数据模型
                    msg:'hello world'
                },
                // 函数
                methods: {
    
    
                    changeData(){
    
    
                      if(this.msg==='hello world'){
    
    
                        // 更改数据模型中的数据
                        // 获取数据模型中的数据
                        // 在vue实例内访问vue实例身上的属性和方法
                        this.msg='你好我是修改后的值'
                      }else{
    
    
                         this.msg='hello world';
                      }
                    }
                },
            })
        }
### html代码
<!-- 以前把msg作为元素文本的,获取dom节点,绑定事件,dom.innerText=msg-->
    <div id="app">
        <!-- 在模板内访问vue实例中数据模型中的数据 插值 -->
        <!-- 基本渲染 插值 -->
        {
    
    {
    
    msg}}
        <p>{
    
    {
    
    msg}}</p>
        <!-- 点击按钮 改变数据模型中的数据msg变量 -->
        <button @click='changeData'>点我修改数据模型msg数据</button>
    </div>
数据模型更改,引发了vm驱动

2.MVVM

​ Model data model

​ View view

​ VM ViewModel is the link between the view and the data model. When the data model changes, vm notifies the view to modify it; when the view changes, vm notifies the data model to make corresponding modifications.

The view model helps us render the data in the data model to the view, which is equivalent to a link

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-wd2QUqbw-1691293440376) (D:\code area\ES6 and vue class documents\images\image-20210527142359964.png )]

Optimized rendering: when the current data model changes, only the corresponding view is changed, and only the corresponding view layer is rendered

Introduction to mvvm:
m refers to the business logic operation on the model server, v refers to the view view (page), vm refers to the core hub between the ViewModel model and the view, such as vue.js

You can think of DOM Listeners and in the above figure Data Bindings as two tools, which are the key to achieving two-way binding.

From the View side, the tools in the ViewModel DOM Listeners will help us monitor the changes of the DOM elements on the page, and if there are changes, change the data in the Model;

From the Model side, when we update the data in the Model, Data Bindings the tool will help us update the DOM elements in the page.

### 2.数据模型
 let vm=new Vue({
    
    
            el:'#app',
            data:{
    
    
               msg:'科大优质男',
			   time:new Date()
            },
            methods:{
    
    
                sayName(){
    
    
                    console.log(this.name)
                },
            }
        })
        // 每隔一秒重新查询一次时间
        setInterval(()=>{
    
    
            vm.time=new Date()
        },1000)
        // 查看vue实例对象
        console.log(vm)

****** **** 3. Life cycle (hook function)

The whole process from vue instance creation to virtual dom generation to data binding monitoring data rendering and destruction

生命周期的第一步首先是创建vue实例,并且进行初始化。
### vue实例初始化阶段
beforeCreate
    在初始化的时候调用了beforeCreate,完成了vue实例的生命周期相关属性的初始化以及事件的初始化。这个时候还不能访问数据模型中的data和methods中的方法。
created
    在初始化完毕之后,完成vue的数据注入以及数据监听操作,该构造的执行意味着vue实例创建完毕,可以进行data数据模型和和methods方法的访问
### vue实例挂载阶段
beforeMount
    在created之后,vue会判断实例中是否含有el属性,如果没有vm.$mount(el),接着会判断是否含有template属性,如果有将其解析为一个render function,如果没有将el指定的外部html进行解析。这里只完成了模板的解析但是数据并没有绑定到模板中。
mounted
	创建vm.$el替换el,实际上完成的是数据绑定操作,在其间执行了render函数,将模板进行了解析,将数据进行了动态绑定
### vue实例更新阶段
	beforeUpdate
    更新虚拟dom节点
    updated
    完成了页面的重新渲染
### vue实例销毁阶段
	beforeDestroy
    销毁之前调用,此时可以访问vue实例
    destroyed
    完成了监听器,子组件,事件监听等移除,销毁vue实例对象。
### js代码
<script>
        let vm=new Vue({
    
    
            el:"#app",
            data:{
    
    
                msg:'hello world'
            },
            beforeCreate(){
    
    
                console.log('vue实例初始化之前')
            },
            created() {
    
    
                console.log('vue实例初始化好了,可以访问到数据模型中的数据以及methods方法')
            },
            beforeMount() {
    
    
                console.log('实例挂载之前')
            },
            mounted(){
    
    
                console.log('实例挂载完毕,可以获取dom节点,一般不操作dom')
            },
            beforeUpdate() {
    
    
                console.log('实例发生改变之前触发该生命周期')
            },
            updated() {
    
    
                console.log('实例发生改变后页面视图发生变化,触发该生命周期')
            },
            beforeDestroy() {
    
    
                // console.log('实例销毁之前,仍然可以访问到数据模型中的数据和方法')
            },
            destroyed() {
    
    
                // console.log('实例销毁完毕,销毁了监听器和事件监听以及子组件');
            },
            methods:{
    
    
                sayHello(){
    
    
                    console.log(this.msg)
                },
            }
        });
        console.log(vm)
        setTimeout(()=>{
    
    
            vm.$destroy()            
        },3000)
    </script>
### html代码
 <div id="app">
        {
    
    {
    
    msg}}
 </div>

4. Template syntax

introduce:

Vue uses an HTML-based template syntax that allows developers to declaratively bind DOM to the data of the underlying Vue instance. All Vue templates are valid HTML, so they can be parsed by spec-compliant browsers and HTML parsers. On the underlying implementation, Vue compiles templates into virtual DOM rendering functions. Combined with the responsive system, Vue can intelligently calculate how many components need to be re-rendered at least, and minimize the number of DOM operations. If you are familiar with virtual DOM and prefer the raw power of JavaScript, you can also directly write rendering functions and render without templates, using optional JSX syntax (react uses jsx syntax).

1. Interpolation: 1. Basic rendering { {}}

​When a Vue instance is created, it adds all the properties in the data object to Vue's reactive system. When the values ​​of these properties change, the view will "response", that is, the matching will be updated with the new values.

渲染最常见的形式就是使用“Mustache”语法 (双大括号) 的文本插值。

2. Original html (v-html, parse the text content in the tag)
3. Attribute v-bind (you can use: abbreviation to indicate that the binding is a variable)
4. Event v-on:click (you can use @ abbreviation)
5.javascript expression (js logic operation can be performed)
 ```Mustache 标签```将会被替代为对应数据对象上 ```msg property```的值。无论何时,绑定的数据对象上 ```msg property ```发生了改变,插值处的内容都会更新。当这些数据改变时,视图会进行重渲染。
1.文本渲染
	### js代码
	let vm=new Vue({
    
    
            el:'#app',
            data:{
    
    
                msg:'hello world',
                animal:['大笨象','小猴子','狐狸']
            },
            methods:{
    
    
            }
        });
	### html代码
   	<div id="app">
        <div>{
    
    {
    
    animal}}</div>
        <div>{
    
    {
    
    msg}}</div>
    </div>
也可以使用v-once指令,执行一次性地插值,当数据发生改变,插值处的内容不会更新
### js代码
	 let vm=new Vue({
    
    
            el:'#app',
            data:{
    
    
                msg:'hello world'
            }
        })
        setTimeout(()=>{
    
    
            vm.msg='hello vue'
        },2000)
### html代码
	<div id="app" >
        <!-- {
    
    {
    
     msg }} 不会再更改,一直是hello world -->
        <div v-once>{
    
    {
    
    msg}}</div>
    </div>
2.如果我们向后台请求的数据是一段HTML代码,如果我们直接通过{
    
    {
    
    }}来输出,会将HTML代码也一起输出。双大括号会将数据解析为普通文本,而非 HTML 代码。但是我们可能希望的是按照HTML格式进行解析,并且显示对应的内容。如果我们希望解析出HTML展示
可以使用**v-html**指令:该指令后面往往会跟上一个string类型,会将string的html解析出来并且进行渲染。
	<div id="app">
        <div v-html='url'></div>
    </div>
	 new Vue({
    
    
            el:'#app',
            data(){
    
    
                return {
    
    
                    list:"All the changan flowers in one day",
                    url:'<a href="https://www.baidu.com">百度一下</a>'
                }
            }
        })
3.属性渲染
双大括号语法不能作用在元素属性上,遇到这种情况应该使用**v-bind**指令 :
	### js代码
	new Vue({
    
    
            el:"#app",
            data(){
    
    
                return {
    
    
                    msg:'我是数据模型中的msg',
                    title:'我是鼠标悬浮就会展示的title'
                }
            }
        })
	### html代码
    <div id="app">
        <!-- <div v-bind:title='title'>{
    
    {
    
    msg}}</div> -->
         <!-- 简写为:属性名="变量名" -->
        <div :title='title'>{
    
    {
    
    msg}}</div>
    </div>
4.事件渲染
可以使用v-on给当前元素绑定事件,也可以使用简写形式@click
 ###js代码
	 new Vue({
    
    
            el:'#app',
            data:{
    
    
            },
            methods:{
    
    
                test(){
    
    
                    alert(1)
                }
            }
        })
 ### html代码
  	<div id="app">
        <button v-on:click='test'>点我点我</button>
        <button @click='test'>点我点我</button>
    </div>
5.javaScript表达式
	###js代码
 	new Vue({
    
    
            el:'#app',
            data(){
    
    
                return {
    
    
                   animal:['大笨象','小猴子','狐狸'],
                   count:1001,
                   firstname:'ren',
                   lastname:'terry'
                }
            }
        })
	###html代码
    <div id="app">
        <ul>
            <li v-for='(item,index) in animal'>
                {
    
    {
    
    index+1}}-{
    
    {
    
    item}}-{
    
    {
    
    index}}
            </li>
        </ul>
        <div>{
    
    {
    
    Number(animal)}}</div>
        <div>{
    
    {
    
    Boolean(animal)}}</div>
        <div>{
    
    {
    
    count*100}}</div>
        <div>{
    
    {
    
    firstname}}--{
    
    {
    
    lastname}}</div>
    </div>

conditional rendering

​ 1. v-if (can be used alone) , when the expression is true, render the element using the v-if attribute, otherwise use v-else to render

​ 2. v-show (toggle display attribute in css style), frequently switch css style, use v-show **

It is not recommended to use v-if and v-for together. When v-if is used with v-for, v-for has higher priority than v-if.

****** v-show 与 v-if 的区别 : v-show 不支持 v-else v-show 不管初始条件是什么,元素总是会被渲染,并且只是简单地基于 CSS 进行切换。 v-if 是“真正”的条件渲染,因为它会确保在切换过程中条件块内的事件监听器和子组件适当地被销毁和重建。 v-if 也是惰性的:如果在初始渲染时条件为假,则什么也不做;直到条件第一次变为真时,才会开始渲染条件块。 v-if 有更高的切换开销,而 v-show 有更高的初始渲染开销。因此,如果需要非常频繁地切换,则使用 v-show 较好;如果在运行时条件很少改变,则使用 v-if 较好。
v-if corresponds to the addition or deletion of elements/labels.
Add elements if conditions
are met. Delete elements if conditions are not met. v-show corresponds to the
display attribute in the element's CSS style.
display: block
does not meet the conditions corresponding to the element's hidden display: none
v-show is used to switch css styles frequently

 	### javascript代码
	new Vue({
    
    
			el:"#app",
			data:{
    
    
				type:'email',
				animal:['老虎','大象','狮子'],
				isShow:false
			}
		})
	### html代码
    <button @click="type='email'">点我获取email</button>
		<button @click="type='telephone'">点我获取telephone</button>
		<div v-if="type=='email'">
			<form>
				<input type="text" placeholder="请输入email">
			</form>
		</div>
		<div v-else-if="type==='telephone'">
			<form >
				<input type="text" placeholder="请输入telephone">
			</form>
		</div>
		<div v-else>错误</div>
		<ul v-show="">
			<li v-for="item in animal" :key="item">{
    
    {
    
    item}}</li>
		</ul>
	</div>

list rendering v-for

Used to render list data. The v-for directive requires a special syntax of the form item in items, where items is the source data array and item is an alias for the array element being iterated over.

*** key

Vue renders elements as efficiently as possible, often reusing existing elements rather than rendering them from scratch. Doing this makes Vue very fast. But sometimes, we don't want vue to be reused. At this time, Vue provides you with a way to express "these two elements are completely independent, don't reuse them". Just add a key with unique value

   ### html代码
		<ul>
            <li v-for='(item,index) in animal' :key='item'>
                {
    
    {
    
    index+1}}-{
    
    {
    
    item}}-{
    
    {
    
    index}}
            </li>
        </ul>
	### js代码
	  new Vue({
    
    
            el:'#app',
            data(){
    
    
                return {
    
    
                   animal:['大笨象','小猴子','狐狸'],
                }
            }
        })

style binding

Manipulating the class list and inline style of an element is a common requirement for data binding, because they are all attributes, so we can use v-bind to handle them: just calculate the string result through the expression. However, string concatenation is cumbersome and error-prone. Therefore, Vue has made special enhancements when using v-bind for class and style. The type of the expression result can be an object or an array in addition to a string.

### html代码
    <div :style="styleObj">Hello</div>
    <div :style="{color:currentColor}">World</div>
    <div :style="[styleObj2,styleObj]"> hello world</div>
### css代码
 new Vue({
    
    
      el: '#app',
      data: {
    
    
        currentColor: 'blue',
        styleObj: {
    
    
          color: 'red',
          "font-size": '30px',
        },
        styleObj2: {
    
    
          background: 'pink',
          color: 'blue'
        }
      },
    })

class binding

Manipulating the class list and inline style of an element is a common requirement for data binding, because they are all attributes, so we can use v-bind to handle them: just calculate the string result through the expression. However, string concatenation is cumbersome and error-prone. Therefore, Vue has made special enhancements when using v-bind for class and style. The type of the expression result can be an object or an array in addition to a string.

  ### css样式
   .red {
    
    
      color: red;
    }
    .size {
    
    
      font-size: 30px;
    }
	### html代码
     <div id="app">
        <div class="red" :class="{size:true}">Hello</div>
        <div :class="{red:false,size:true}">World</div>
        <div :class="[{red:true},{size:false}]">hello World</div>
  	</div>
	### js代码
     new Vue({
    
    
      el: '#app',
      data: {
    
    
      
      },
    })

********* [Interview question: Why is data a function instead of an object in large projects]

组件是一个可复用的实例,当你引用一个组件的时候,组件里的data是一个普通的对象,所有用到这个组件的都引用的同一个data,就会造成数据污染。

不使用return包裹的数据会在项目的全局可见,会造成变量污染;
使用return包裹后数据中变量只在当前组件中生效,不会影响其他组件。
当一个组件被定义, data 必须声明为返回一个初始数据对象的函数,因为组件可能被用来创建多个实例。如果 data 仍然是一个纯粹的对象,则所有的实例将共享引用同一个数据对象!通过提供 data 函数,每次创建一个新实例后,我们能够调用 data 函数,从而返回初始数据的一个全新副本数据对象。
//1、在简单的vue实例中看到的Vue实例中data属性,如下所示:
<script>
  let vm=new Vue({
    
    
    el:'',
    data:{
    
    },//数据可以直接挂在vue实例上
    methods:{
    
    }
  })
</script>
//2、在使用组件化的项目中,如下所示:
//每一个.vue文件中都对应一个vue组件实例,该vue组件实例的构造函数参数由当前页面的export default提供
<script>
  export default{
    
    
  	data(){
    
    
		return {
    
    
          
      	}
	},
    methods:{
    
    
	}
</script>
```
It is officially recommended that we add a :key attribute to the corresponding element or component when using v-for.
Why do you need this key attribute (understand)?

This is actually related to the Diff algorithm of Vue's virtual DOM.

When there are many same nodes in a layer, that is, list nodes, we want to insert a new node
  • We hope that an F can be added between B and C, and the Diff algorithm is executed like this by default.
  • That is, update C to F, D to C, E to D, and finally insert E, isn't it very inefficient?
    insert image description here
So we need to use key to uniquely identify each node
  • The Diff algorithm can correctly identify this node

  • Find the correct location area to insert the new node.

So in a word, the function of key is mainly to update the virtual DOM efficiently.

![[External link image transfer...(img-NxoOjIU8-1691293440378)]](https://img-blog.csdnimg.cn/327e67c95dc4415c8d3a34109e611626.

Guess you like

Origin blog.csdn.net/qq_63299825/article/details/132129250