Introduction to template syntax based on Vue

Table of contents

1. General introduction of Vue

2. MVVM model

3. Template syntax

1. Interpolation syntax { {}}

2. v-html command

3. v-bind command

4. v-on command

5. Conditional rendering

6. List rendering v-for

7. Style binding and class binding


1. General introduction of Vue

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 applications, and the vue plug-in routing used for page jumps to achieve jumps.

Vue official website: https://cn.vuejs.org/

The vue official website has been updated to vue3, but we still start with vue2.

Before we use vue, we need to introduce the vue framework first, and go directly to the official website to copy the script tag:

Learn -> Tutorial -> Install:

 Vue basic use:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<!-- 引入vue框架 -->
	<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</head>
<body>
	<!-- 模板 根组件只有一个模板-->
	<div  id="app">
		<!-- 文本插值 -->
		{
   
   {msg}}
		<br>----------------------------
		<my-info></my-info>
		<my-info></my-info>
		<my-info></my-info>
		{
   
   {qq}}
		<!-- 事件绑定 使用v-on:事件类型='函数名' -->
		<!-- @事件类型 绑定事件 -->
		<!-- <button v-on:click="handler">获取qq</button> -->
		<button @click="qq='111222333'">获取qq</button>
		{
   
   {time}}
	</div>
	<script>
		// 自己定义组件实例
		let Info={
			template:`
				<div>{
   
   {msg}}</div>
			`,
			// data:{
			// 	msg:"hello world"
			// }
			data(){
				return {
					msg:"hello world"
				}
			}
		};
		// 创建vue实例 Vue构造函数方式
		let vm=new Vue({
			// 局部注册组件实例
			components:{
				'my-info':Info
			},
			// 将模板与实例进行绑定
			el:"#app",
			// 数据模型 存放vue变量
			data:{
				msg:'hello Vue2',
				qq:'获取qq',
				time:new Date()
			},
			// 声明函数 
			methods:{
				handler(){
					this.qq='111222333'
				}
			}
		});
		setInterval(()=>{
			vm.time=new Date()
		},1000);
	</script>
</body>
</html>

2. MVVM model

MVVM model:

  • M : Model Model, corresponding to the data in data
  • V : View View, corresponding to the template in vue
  • VM : view model ViewModel, corresponding to Vue instance object

You can think ofDOM Listeners(dom监听器) and in the above figure as two tools, which are the key to realizing two-way data binding:Data Bindings(数据绑定)

  • From the View side, the tools in the ViewModel DOM Listenerswill 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 Bindingsthe tool will help us update the DOM elements in the page.

To put it simply: 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.

Vue draws on the MVVM model:

3. Template syntax

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.

1. Interpolation syntax { {}}

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

  • The most common form of rendering is text interpolation using the "Mustache" syntax (double braces)
  • Any js expression can be written inside the double braces
  • Use the v-once command to perform a one-time interpolation. When the data changes, the content at the interpolation will not be updated
<body>
  <div id="app">
    <!-- 1.文本插值 mustache语法 {
   
   {}} -->
    {
   
   {msg}}
    <!-- 2.{
   
   {使用js表达式}} -->
	{
   
   {count * 100}}
	{
   
   {Number(msg)}}
	{
   
   {Boolean(msg)}}
    <!-- 3. v-once 使用v-once指令,执行一次性的插值,当数据发生改变,插值处的内容不会更新 -->
    <div v-once>{
   
   {msg}}</div>
  </div>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        msg: 'hello Vue',
        count: 10
      }
    });
    //设置两秒后修改msg的值,使用v-once后插值处内容不会改变
    setTimeout(()=>{
			vm.msg='我被修改了'
		},2000)
  </script>
</body>

2. v-html command

If the data we request from the background is a piece of HTML code, if we output it directly through { {}}, the HTML code will also be output together. Double curly braces will parse the data as plain text, not HTML code. But what we may want is to parse according to HTML format and display the corresponding content. If we want to parse out the HTML display, we can use the v-html command: this command is often followed by a string type, which will parse out the HTML of the string and render it.

<body>
  <div id="app">
    <!-- 使用插值语法无法解析html代码片段 -->
    {
   
   {p}}
    <!-- 使用v-html指令可以解析代码片段 -->
    <div v-html="p"></div>
  </div>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        p:'<a href="https://www.baidu.com">百度一下</a>'
      }
    });
  </script>
</body>

The result is as follows:

 

3. v-bind command

The double curly braces syntax cannot be applied to element attributes. In this case, the v-bind command should be used.

The v-bind directive can be abbreviated as a colon:

<body>
  <div id="app">
    <!-- 绑定变量 v-bind 或者 简写成: -->
    <div v-bind:title="title">hello vue</div>
    <div :title="title">hello world</div>
  </div>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        title: "我是一个标题"
      }
    });
  </script>
</body>

4. v-on command

You can use v-on to bind events to the current element, or you can use the short form @

<body>
  <div id="app">
    {
   
   {msg}}
    <!-- 绑定事件 v-on:事件名称="函数名(或者直接写js代码)"-->
    <button v-on:click="update">点击我</button>
    <!-- 简写 @ -->
    <button @click="msg='我又被修改了'">点击我</button>
  </div>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        msg: "hello vue"
      },
      methods:{
        update(){
          this.msg = '我被修改了'
        }
      }
    });
  </script>
</body>

 

5. Conditional rendering

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;

v-show (switch the 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.

The difference between v-if and v-show:

v-if is a lazy dom overhead. The dom node will be loaded only when the condition is met, and the dom element will not be rendered directly if the condition is not met. Usage scenario: used when there is less dom overhead.

v-show displays the element when the condition is met, and calls display:none to hide the element when the condition is not met, but loads the dom element regardless of whether the condition is met. Usage scenario: used when frequent switching of css styles is required.

<body>
  <div id="app">
    <!-- 条件渲染 v-if v-else-if v-else v-show-->
    <div v-if="type==='email'">
      <form>
        <input type="text" placeholder="请输入邮箱">
      </form>
    </div>
    <div v-else-if="type==='telephone'">
      <form>
        <input type="text" placeholder="请输入电话">
      </form>
    </div>
    <div v-else>错误</div>
    <div v-show="isShow">我是一个div</div>
  </div>
  <script>
    new Vue({
      el: "#app",
      data: {
        type: "telephone",
        isShow: false
      }
    })
  </script>
</body>

6. List rendering v-for

v-for is 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 elements being iterated over.

key attribute

When using v-for, we need to add a :key attribute to the corresponding element or component.

Why is this key attribute needed?

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?

 

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.

<body>
  <div id="app">
    <!-- 列表渲染数组 -->
    <ul>
      <li v-for="(item,index) in animal" :key="item">{
   
   {item}}--{
   
   {index}}</li>
    </ul>
    <!--列表渲染对象 -->
    <ul>
      <li v-for="(key,value,index) in obj" :key="index">{
   
   {key}}--{
   
   {value}}--{
   
   {index}}</li>
    </ul>
  </div>
  <script>
    new Vue({
      el: "#app",
      data: {
        animal: ['老虎', '猴子', '狮子'],
        obj: {
          name: 'zhangsan',
          age: 18
        }
      }
    })
  </script>
</body>

 

7. Style binding and class binding

Manipulating the class list and inline styles of elements 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.

<style>
	.red{
		color:red;
	}
	.color{
		font-size: 18px;
		background-color: pink;
	}
</style>
<body>
	<div id="app">
        <!-- 动态绑定style -->
		<div :style="{color:currentColor}">我是一个div</div>
		<div :style="styleObj1">我是第二个div</div>
		<div :style="[styleObj1,styleObj2]"> 我是第三个div</div>
		<!-- 动态绑定类名 -->
		<div :class="{red:true}">我是第四个div</div>
		<div :class="{red:false,color:true}">我是第五个div</div>
		<div :class="[{red:true},{color:false}]">我是第六个div</div>
	</div>
	<script>
		new Vue({
			el:"#app",
			data:{
				currentColor:'red',
				styleObj1:{
					fontSize:'18px',
					backgroundColor:'blue'
				},
				styleObj2:{
					backgroundColor:'red'
				}
			}
		})
	</script>
</body>

Guess you like

Origin blog.csdn.net/lq313131/article/details/126997597