search
HomeWeb Front-endJS TutorialDetailed explanation of the most complete usage of Vue.js

Detailed explanation of the most complete usage of Vue.js

Dec 21, 2017 pm 01:20 PM
javascriptvue.jsDetailed explanation

Vue.js is a progressive framework for building user interfaces. It only focuses on the view layer and adopts a bottom-up incremental development design. The goal is to achieve responsive data binding and combined views through the simplest possible API. components. Vue is very easy to learn. This tutorial is based on Vue 2.1.8 version test. It is very popular in programming. This article mainly introduces the detailed usage of Vue.js. Friends who need it can refer to it. I hope it can help everyone.

First of all, let’s take a look at Vue:

Vue.js is a progressive framework for building user interfaces. Unlike other heavyweight frameworks, Vue fundamentally adopts a minimum-cost, incrementally adoptable design. Vue's core library focuses solely on the view layer and is easy to integrate with other third-party libraries or existing projects. On the other hand, when combined with single-file components and libraries supported by the Vue ecosystem, Vue is also perfectly capable of powering complex single-page applications. Therefore, Vue is actually very powerful.

1.Vue.js installation and template syntax

The use of Vue is very simple. You can directly download Vue.js or import Vue.min.js to use it.

1-1 Template Syntax

Vue.js uses HTML-based template syntax, allowing developers to declaratively bind the DOM to the data of the underlying Vue instance.

At its core, Vue.js is a system that allows you to declaratively render data into the DOM using concise template syntax.

Combined with the response system, when the application state changes, Vue can intelligently calculate the minimum cost of re-rendering the component and apply it to DOM operations.

1. html template

html template: DOM-based template, the templates are parsable and valid HTML

Interpolation:

Text: use "Mustache" syntax (braces) {{ value }}; Function: Replace the attribute value on the instance. When the value changes, the interpolated content will be automatically updated. You can also use v-text="value" instead.

  <p>{{ value }}</p><p> 等价于 </p><p></p>

Native HTML: The text output by double curly brackets will not parse the HTML tag. That is to say, when the data of the instance is an html tag, it cannot be parsed but output directly. If you want to parse at this time, you can use v-html="value" instead.

new Vue({
  data:{
    value: `<span>我是一个span标签</span>`
  }
});
<p>{{ value }}</p><p>  页面展示 => <span>我是一个span标签</span> 
</p><p></p><p>  页面展示 => 我是一个span标签</p>

It should be noted that sometimes due to some network delays and other reasons, users will first see {{ xxx }} in the middle of the purchase period, and then have data. If we want to avoid this effect, we can use v-text="xxxx" instead.

Properties: Use v-bind for binding, which can respond to changes.

Title

=> Note that show here is a Boolean value in data. If true, red will be added. class, if false, remove the red class,

Use javascript expressions: you can write simple expressions. (Simple ternary operations are possible, but if statements cannot be written). There will be calculated attributes in the future.

{ 1+2 }
{ true? "yes":"no" }

2. String template

template string

tempalte => The attribute of the option object

The template will replace the mount Elements. The content of the mounted element will be ignored. There is only one root node. Write the HTML structure in a pair of script tags and set type="x-template".

  <p>

  </p>

<script></script>
<script>
  document.addEventListener(&#39;DOMContentLoaded&#39;,function () {
    var str = &#39;<h2>hello pink!&#39;
    var vm = new Vue({
      el: &#39;#box&#39;,
      template: str
    });
  },false);
</script>

Indicates that the weight is relatively high, directly "replace" the mount point, replace the original html and display it.

//代码片段这个就是利用script标签对内定义模版,局限性:不能跨文件使用,一个页面中可以使用

  <p>

  </p>

<script></script>
<script>
  <p>我是一个p标签
</script>
<script>
  document.addEventListener(&#39;DOMContentLoaded&#39;,function () {
    var vm = new Vue({
      el: &#39;#box&#39;,
      template: &#39;#str&#39;
    });
  },false);
</script>

Vue instance, each application creates a root instance (root instance) through the Vue constructor to start New Vue (option object). You need to pass in the options object, which contains hanging elements, data, templates, methods, etc.

el: Mount element selector --- String|HtmlElement
data: Proxy data --- Object|Function
methods: Definition method --- Object

Vue Proxy data data. Each Vue instance will proxy all properties in its data object. These proxied properties are responsive. The newly added attributes are not responsive and the view will not be updated after changes.

The Vue instance's own properties and methods expose its own properties and methods, starting with "$", such as: $el, $data. . .

var vm = new Vue({
    el: '#app',
    data: {
     message: 'hello,Datura!!!'
    },
    methods: {
      test (){
        alert(1);
      }
    },
    compontents:{
    //这里存放组件
    }
   });
 /* vm就是new出来的实例 */
 console.log(vm.$data);//也就是数据data,后面还有很多挂载在vm(new出来的)实例上的属性
//代码片段放在template标签里,并给一个id名

  <template>
    <p>我是template</p>
  </template>
  <p>

  </p>

<script></script>
<script>
  document.addEventListener(&#39;DOMContentLoaded&#39;,function () {
    var vm = new Vue({
      el: &#39;#box&#39;,
      template: &#39;#tem&#39;
    });
  },false);
</script>

3. Template—render function

render function is very close to the editor
render => Option object properties

Data object properties

class: {}, => 绑定class,和v-bind:class一样的API
style: {}, => 绑定样式,和v-bind:style一样的API
attrs: {}, => 添加行间属性
domProps: {}, => DOM元素属性
on: {}, => 绑定事件
nativeOn: {}, => 监听原生事件
directives: {}, => 自定义指令
scopedSlots: {}, => slot作用域
slot: {}, => 定义slot名称 和组件有关系,插曹
key: "key", => 给元素添加唯一标识
ref: "ref", => 引用信息
2Vue.js的条件、循环语句
2-1条件语句
v-if :根据值的真假,切换元素会被销毁、重建; => 在dom中已消失
v-show :根据值的真假,切换元素的display属性;
v-else :条件都不符合时渲染;
v-else-if :多条件判断,为真则渲染;

1. V-if

Conditional judgment uses the v-if instruction:

<p>
  </p><p>现在你看到我了</p>
  <template>
   <p>哈哈哈,打字辛苦啊!!!</p>
  </template>
  
<script>
new Vue({
 el: &#39;#app&#39;,
 data: {
  seen: true,
  ok: true
 }
})
</script>

Here, the v-if instruction will determine whether to insert p based on the value of the expression seen (true or false) element.

2. v-else

You can use the v-else instruction to add an "else" block to v-if:

Randomly generate a number and determine whether it is greater than 0.5. Then output the corresponding information:

<p>
  </p><p> 0.5">
   Sorry
  </p>
  <p>
   Not sorry
  </p>

  
<script>
new Vue({
 el: &#39;#app&#39;
})
</script>

3. v-show

We can also use the v-show command to display elements based on conditions:

<p>
  </p><h1 id="Hello">Hello!</h1>

<script>
new Vue({
 el: &#39;#app&#39;,
 data: {
  ok: true
 }
})
</script>

4. v-else- if

v-else-if was added in 2.1.0. As the name suggests, it is used as the else-if block of v-if. Can be used multiple times in a chain:

Judge the value of the type variable:

<p>
  </p><p>
   A
  </p>
  <p>
   B
  </p>
  <p>
   C
  </p>
  <p>
   Not A/B/C
  </p>
 
<script>
new Vue({
 el: &#39;#app&#39;,
 data: {
  type: &#39;C&#39;
 }
})
</script>

[Use and comparison of v-show and v-if]

① v-show : Switch the display attribute of the element based on the true or false value;

v-show elements will always be rendered and remain in the DOM.

v-show does not support template syntax.

② v-if is a true conditional rendering, because it will ensure that the conditional block properly destroys and rebuilds the event listeners and subcomponents within the conditional block during the switch.

③ v-if有更高的切换消耗而v-show有更高的初始渲染消耗。

如果需要频繁切换使用v-show更好,如果在运行时条件不大可能改变,使用v-if比较好

2-2      循环语句       v-for

① 语法:v-for="x in items"

    x是索引;items是数组,这样进行遍历

② v-for循环是不断创建新的标签,标签里的内容,我们决定,一般都是放在数组里,然后遍历显示出来。也可以放对象 ,遍历对象。

③ 当 v-if 与 v-for 一起使用时,v-for 具有比 v-if 更高的优先级。

  <p>
    </p>
          
  • {{ val }} => {{ key }}
  •  //循环出来的列表项     
   <script></script> <script> document.addEventListener(&#39;DOMContentLoaded&#39;,function () { var vm = new Vue({ el: &#39;#app&#39;, data:{ fruitsArr:[&#39;apple&#39;,&#39;banana&#39;,&#39;orage&#39;,&#39;pear&#39;] //数据源 } }); },false); </script>

总结

以上所述是小编给大家介绍的Vue.js用法详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

学完本文之后相信大家对Vue.js有一个更深的了解,大家觉得不错的话就收藏起来吧。

相关推荐:

最详细的vue.js安装教程

实用的vue.js项目中小技巧汇总

Vue.js常用指令的学习详解

The above is the detailed content of Detailed explanation of the most complete usage of Vue.js. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools