Home > Web Front-end > JS Tutorial > body text

Explain in detail how to use components and their functions in Vue.js?

亚连
Release: 2018-06-08 14:04:05
Original
3398 people have browsed it

Component (Component) is one of the most powerful features of Vue.js. Components can extend HTML elements, encapsulating reusable code. This article mainly introduces the components in vue.js. Friends who need it can refer to

Introduction

When using Vue.js, Vue.js components are very important. In this tutorial, we'll delve into Vue.js components, understand the basics, and apply them to your application. let's start.

What are components?

Components allow us to break complex applications into small pieces. For example, a typical web application will have sections such as header, sidebar, content, and footer.

Vue.js allows us to break each part into separate modular code, called components. These components can be extended and then attached to the application you are working on. Using components is a great way to reuse code throughout your application writing.

Suppose you have a blog application, and you want to display a column of blog posts. Using Vue components, you can do:

<blog-post></blog-post>
Copy after login

Vue handles the rest.

Create a simple HTML page that mounts a Vue instance to a DOM element. You'll use it to learn about components. The following is a sample HTML page:

<!DOCTYPE html>
<html>
<head>
<title>VueJs Components</title>
</head>
<body>
 <!-- p where Vue instance will be mounted -->
 <p id="app"></p>
 
 <!-- Vue.js is included in your page via CDN -->
 <script src="https://unpkg.com/vue"></script>
 <script>
  // A new Vue instance is created and mounted to your p element
  new Vue({
   el: &#39;#app&#39;,
   data: {
   domain: &#39;Tutsplus&#39;
   },
   template: &#39;<p>Welcome to {{ domain }}</p>
  });
 </script>
</body>
</html>
Copy after login

Above, you created a simple Vue instance with no components in the code. Now, if you want the welcome message to appear twice, then what do you do?

Your guess may be to let p appear twice where the Vue instance is mounted. this will not work. Try changing it from id to class and you will get:

<!DOCTYPE html>
<html>
<head>
<title>VueJs Components</title>
</head>
<body>
 <!-- p where Vue instance will be mounted -->
 <p class="app"></p>
 <p class="app"></p>
 
 <!-- Vue.js is included in your page via CDN -->
 <script src="https://unpkg.com/vue"></script>
 <script>
  // A new Vue instance is created and mounted to your p element
  new Vue({
   el: &#39;.app&#39;,
   data: {
   domain: &#39;Tutsplus&#39;
   },
   template: &#39;<p>Welcome to {{ domain }}</p>
  });
 </script>
</body>
</html>
Copy after login

It still won't work!

The only way to solve this problem is to create a component. How do you create a component?

Components are created using the Vue.component() constructor. This constructor takes two parameters: the name of your component (also called the tag name) and an object containing the component options.

Let’s create a component using the above content.

Vue.component(&#39;welcome-message&#39;, {
  data: function() {
  return {
   domain: &#39;Tutsplus&#39;
  }
  },
  template: &#39;<p>Welcome to {{ domain }}</p>&#39;
 })
Copy after login

Above, the component name is called welcome-message. Your component can have any name you choose. Importantly however, this name does not affect any HTML tags as you do not want to override it.

The options object passed to the constructor contains data and templates. When creating a component, your data should be a function, as seen above. The saved data should be returned as an object.

With no data to pass, pass a template like this:

 Vue.component(&#39;welcome-message&#39;, {
  template: &#39;<p>Welcome to Tutsplus</p>&#39;
 })
Copy after login

Once you're done, you can treat it as a regular HTML element in your application by using the name passed to the constructor components used in. It is called like this: <welcome-message> </ welcome-message>.

To output the template multiple times, you can call the component as many times as needed, as shown below.




VueJs Components


 
 

<script> Vue.component(&amp;#39;welcome-message&amp;#39;, { data: function() { return { domain: &amp;#39;Tutsplus&amp;#39; } }, template: &amp;#39;&lt;p&gt;Welcome to {{ domain }}&lt;/p&gt;&amp;#39; }) // A new Vue instance is created and mounted to your p element new Vue({ el: &#39;#app&#39; }); </script>
Copy after login

In this way, the welcome message will be displayed four times.

Storing data in components

I mentioned above that the data must be a function, and the information it contains must be returned as an object. why is it like this?

When the returned data is not an object, the components using the data share the same source: shared data. Therefore, data changes in one component will affect another component. This is not the same when the data is returned as an object.

It's important to see how this actually works. First, let's look at the case where the data is returned as an object.

<!DOCTYPE html>
<html>
<head>
<title>VueJs Components</title>
</head>
<body>
 <!-- p where Vue instance will be mounted -->
 <p id="app">
 <welcome-message></welcome-message>
 <welcome-message></welcome-message>
 </p>
 
 <!-- Vue.js is included in your page via CDN -->
 <script src="https://unpkg.com/vue"></script>
 <script>
 var data = { name: &#39;Henry&#39; }
 
 Vue.component(&#39;welcome-message&#39;, {
  data: function() {
  return data
  },
  template: &#39;<p>Hello {{ name }}, welcome to TutsPlus (<button @click="changeName">Change Name</button>)</p>&#39;,
  methods :{
   changeName: function() {
   this.name = &#39;Mark&#39;
   }
  }
 })
 
 // A new Vue instance is created and mounted to your p element
 new Vue({
  el: &#39;#app&#39;
 });
 </script>
</body>
</html>
Copy after login

Can you guess what happened above?

There are two components, and both components share the same data source because the data is not returned as an object. How do you prove I'm right? When viewing the above page from a browser, you will see that changes in one component cause data in another component to change. So what should it look like?

Like this:

<!DOCTYPE html>
<html>
<head>
<title>VueJs Components</title>
</head>
<body>
 <!-- p where Vue instance will be mounted -->
 <p id="app">
 <welcome-message></welcome-message>
 <welcome-message></welcome-message>
 </p>
 
 <!-- Vue.js is included in your page via CDN -->
 <script src="https://unpkg.com/vue"></script>
 <script>
 
 Vue.component(&#39;welcome-message&#39;, {
  data: function() {
  return {
   name: &#39;Henry&#39;
  }
  },
  template: &#39;<p>Hello {{ name }}, welcome to TutsPlus (<button @click="changeName">Change Name</button>)</p>&#39;,
  methods :{
   changeName: function() {
   this.name = &#39;Mark&#39;
   }
  }
 })
 
 // A new Vue instance is created and mounted to your p element
 new Vue({
  el: &#39;#app&#39;
 });
 </script>
</body>
</html>
Copy after login

The data here is returned as an object, and changes in one component will not affect another component. This function is performed for a single component. It's important not to forget this when building your application.

Creating and using components

Using what we have learned so far, let's implement this by starting a new Vue.js project from scratch using vue -cli. If vue-cli is not installed on your machine, you can start your new Vue.js project by running:

npm install -g vue-cli
Copy after login

:

vue init webpack vue-component-app
Copy after login

Navigate to your application and install the dependencies , and run your development server using the command below.

cd vue-component-app
npm install
npm run dev
Copy after login

First, you will rename the HelloWorld component, which is the component you created when you initialized the application to Hello.vue. You will then register this component as a global component for use in your application.

So your Hello component should look like this.

#src/components/Hello.vue
<template>
 <p class="hello">
 <p>Welcome to TutsPlus {{ name }}</p>
 <hr>
 <button @click="changeName">Change Display Name</button>
 </p>
</template>
<script>
export default {
 name: &#39;Hello&#39;,
 data () {
 return {
  name: &#39;Henry&#39;
 }
 },
 methods: {
 changeName () {
  this.name = &#39;Mark&#39;
 }
 }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
 font-weight: normal;
}
ul {
 list-style-type: none;
 padding: 0;
}
li {
 display: inline-block;
 margin: 0 10px;
}
a {
 color: #42b983;
}
</style>
Copy after login

You have the welcome text showing the welcome message and the name passed as data. When the button below the welcome message is clicked, the changeName method is called. The name will be changed from Henry to Mark.

To use this component globally, it must be registered. Can you guess where this should be done? If you said main.js, congratulations, you got the answer right!

要注册一个组件,可以导入它,然后使用Vue.component()构造函数进行设置。自己动手试试。

我敢打赌,这个对你来说小菜一碟。以下是main.js文件中的内容。

#src/main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from &#39;vue&#39;
import App from &#39;./App&#39;
import Home from &#39;./components/Hello&#39;
Vue.config.productionTip = false
Vue.component(&#39;display-name&#39;, Home)
/* eslint-disable no-new */
new Vue({
 el: &#39;#app&#39;,
 template: &#39;<App/>&#39;,
 components: { App }
})
Copy after login

这里除了导入你的Hello组件的那一行之外,没有什么新东西。然后使用构造函数注册该组件。最后,对于这部分,组件需要使用你输入的组件名称来显示。在这种情况下,组件是显示名称。这将在你的App.vue文件中完成。

打开src / App.vue并使其看起来像这样。

#src/App.vue
<template>
<p id= "app" >
<display-name/>
</p>
</template>
<script>
export default {
}
</script>
<style>
#app {
font-family: &#39;Avenir&#39; , Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Copy after login

打开服务器,打开http:// localhost:8080。 点击按钮,名称应该改变。

我们来看看如何在本地使用一个组件。

在组件目录中创建一个名为Detail.vue的文件。 这个组件不会做任何特殊的事情 - 它将被用在Hello组件中。

使你的Detail.vue文件就像这样。

#src/components/Detail.vue
<template>
 <p class="hello">
 <p>This component is imported locally.</p>
 </p>
</template>
<script>
export default {
 name: &#39;Detail&#39;
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
 font-weight: normal;
}
ul {
 list-style-type: none;
 padding: 0;
}
li {
 display: inline-block;
 margin: 0 10px;
}
a {
 color: #42b983;
}
</style>
Copy after login

要在Hello组件中使用它,可以像导入Hello组件一样将其导入。 接下来,把它注册,但这次你不需要使用Vue.component()构造函数。

你可以使用导出内的组件对象进行注册。将用作元素标记的组件的名称必须作为值传递给对象。 完成后,你现在可以使用元素标记来输出组件。

为了理解这一点,Hello组件应该长这样:

#src/components/Hello.vue
<template>
 <p class="hello">
 <p>Welcome to TutsPlus {{ name }}</p>
 <hr>
 <button @click="changeName">Change Display Name</button>
 <!-- Detail component is outputted using the name it was registered with -->
 <Detail/>
 </p>
</template>
<script>
// Importation of Detail component is done
import Detail from &#39;./Detail&#39;
export default {
 name: &#39;HelloWorld&#39;,
 data () {
 return {
  name: &#39;Henry&#39;
 }
 },
 methods: {
 changeName () {
  this.name = &#39;Mark&#39;
 }
 },
 /**
 * Detail component gets registered locally.
 * This component can only be used inside the Hello component
 * The value passed is the name of the component
 */
 components: {
 Detail
 }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
 font-weight: normal;
}
ul {
 list-style-type: none;
 padding: 0;
}
li {
 display: inline-block;
 margin: 0 10px;
}
a {
 color: #42b983;
}
</style>
Copy after login

刷新页面以查看新页面。

范围组件样式

Vue.js允许你为组件提供全局和本地样式。是什么意思呢?在某些情况下,你希望组件中的某些元素与另一个组件中的对应元素的样式不同。Vue.js能够帮助你。

一个很好的例子是你刚刚建立的小应用程序。App.vue中的样式是全局的; 这怎么可能? 打开你的App.vue,风格部分看起来像这样。

<style>
#app {
 font-family: &#39;Avenir&#39;, Helvetica, Arial, sans-serif;
 -webkit-font-smoothing: antialiased;
 -moz-osx-font-smoothing: grayscale;
 text-align: center;
 color: #2c3e50;
 margin-top: 60px;
}
</style>
Copy after login

这与Detail.vue不同,看起来像这样。

<style scoped>
h1, h2 {
 font-weight: normal;
}
 
ul {
 list-style-type: none;
 padding: 0;
}
 
li {
 display: inline-block;
 margin: 0 10px;
}
 
a {
 color: #42b983;
}
</style>
Copy after login

将   scoped 添加到样式标签是造成这个差别的原因。 尝试通过删除   scoped 来编辑一种组件样式,你会看到这是如何运作的。

结论

虽然这个文章有点长,但是我相信你会喜欢它。

现在你知道如何有效地使用组件,并且了解如何在现有应用程序中构建组件。在使用vue-cli时,你还可以在本地和全局范围内创建和使用组件。当你想为一个组件使用特定的风格时,你已经看到了如何使用scoped来做到这一点。

你现在可以继续构建使用组件的复杂Vue.js应用程序。了解Vue.js允许你重用代码,你的页眉,页脚,登录面板和搜索栏可以用作组件。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在vue中如何使用ztree(详细教程)

使用JS如何实现瀑布流插件

在JS中如何实现将html转为pdf功能

The above is the detailed content of Explain in detail how to use components and their functions in Vue.js?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template