Home >Web Front-end >JS Tutorial >Detailed explanation of using components in Vue.js

Detailed explanation of using components in Vue.js

php中世界最好的语言
php中世界最好的语言Original
2018-04-13 09:27:111547browse

This time I will bring you a detailed explanation of the use of components in Vue.js. What are the precautions for using components in Vue.js? Here are practical cases, let’s take a look.

introduce

Vue.js components are very important when using Vue.js. 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>

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: '#app',
   data: {
   domain: 'Tutsplus'
   },
   template: '<p>Welcome to {{ domain }}</p>
  });
 </script>
</body>
</html>

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 is probably to have 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: '.app',
   data: {
   domain: 'Tutsplus'
   },
   template: '<p>Welcome to {{ domain }}</p>
  });
 </script>
</body>
</html>

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 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('welcome-message', {
  data: function() {
  return {
   domain: 'Tutsplus'
  }
  },
  template: '<p>Welcome to {{ domain }}</p>'
 })

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.

When there is no data to pass, pass the following template:

 Vue.component('welcome-message', {
  template: '<p>Welcome to Tutsplus</p>'
 })

Once this is done, the component can be used in your application by treating it as a regular HTML element using the name passed to the constructor. 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('welcome-message', {   data: function() {   return {    domain: 'Tutsplus'   }   },   template: '&lt;p&gt;Welcome to {{ domain }}&lt;/p&gt;'  })    // A new Vue instance is created and mounted to your p element  new Vue({   el: '#app'  });  </script>

As a result, the welcome message will be displayed four times.

Store data in components

Above I mentioned 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: the 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 works in practice. 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: 'Henry' }
 
 Vue.component('welcome-message', {
  data: function() {
  return data
  },
  template: '<p>Hello {{ name }}, welcome to TutsPlus (<button @click="changeName">Change Name</button>)</p>',
  methods :{
   changeName: function() {
   this.name = 'Mark'
   }
  }
 })
 
 // A new Vue instance is created and mounted to your p element
 new Vue({
  el: '#app'
 });
 </script>
</body>
</html>

Can you guess what's happening 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('welcome-message', {
  data: function() {
  return {
   name: 'Henry'
  }
  },
  template: '<p>Hello {{ name }}, welcome to TutsPlus (<button @click="changeName">Change Name</button>)</p>',
  methods :{
   changeName: function() {
   this.name = 'Mark'
   }
  }
 })
 
 // A new Vue instance is created and mounted to your p element
 new Vue({
  el: '#app'
 });
 </script>
</body>
</html>

The data here is returned as an object, and changes to 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.

Create and use components

使用到目前为止学到的内容,让我们使用 vue -cli 从头开始一个新的Vue.js项目来实现它。 如果你的机器上没有安装 vue -cli ,你可以通过运行:

npm install -g vue-cli

开始你的新的Vue.js项目:

vue init webpack vue-component-app

导航到你的应用程序,安装依赖关系,并使用下面的命令运行你的开发服务器。

cd vue-component-app
npm install
npm run dev

首先,你将重命名HelloWorld组件,这个组件是你将应用程序初始化为Hello.vue时创建的组件。然后你将注册这个组件作为一个全局组件在你的应用程序中使用。

所以你的Hello组件应该看起来像这样。

#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: 'Hello',
 data () {
 return {
  name: 'Henry'
 }
 },
 methods: {
 changeName () {
  this.name = 'Mark'
 }
 }
}
</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>

你有欢迎文本显示欢迎消息和作为数据传递的名称。 当点击欢迎消息下方的按钮时,将调用changeName方法。 名字将从亨利改为马克。

要全局使用此组件,必须被注册。你能猜到应该在哪里完成这个操作吗?如果你说main.js,恭喜你,答对了!

要注册一个组件,可以导入它,然后使用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 'vue'
import App from './App'
import Home from './components/Hello'
Vue.config.productionTip = false
Vue.component('display-name', Home)
/* eslint-disable no-new */
new Vue({
 el: '#app',
 template: '<App/>',
 components: { App }
})

这里除了导入你的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: 'Avenir' , Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>

打开服务器,打开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: '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>

要在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 './Detail'
export default {
 name: 'HelloWorld',
 data () {
 return {
  name: 'Henry'
 }
 },
 methods: {
 changeName () {
  this.name = 'Mark'
 }
 },
 /**
 * 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>

刷新页面以查看新页面。

范围组件样式

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

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

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

这与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>

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

结论

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

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

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

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

mysql连接池怎样使用事务自动回收(附代码)

Angular的浏览器插件Batarang使用详解

The above is the detailed content of Detailed explanation of using components in 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