Vue.js에서 구성요소와 해당 기능을 사용하는 방법을 자세히 설명해주세요.

亚连
풀어 주다: 2018-06-08 14:04:05
원래의
3348명이 탐색했습니다.

Component는 Vue.js의 가장 강력한 기능 중 하나입니다. 구성 요소는 HTML 요소를 확장하여 재사용 가능한 코드를 캡슐화할 수 있습니다. 이번 글에서는 주로 vue.js에 있는 컴포넌트를 소개합니다. 필요한 친구들은

소개

를 참고하시면 됩니다. Vue.js를 사용할 때 Vue.js 컴포넌트는 매우 중요합니다. 이 튜토리얼에서는 Vue.js 구성 요소를 자세히 살펴보고 기본 사항을 이해한 후 애플리케이션에 적용해 보겠습니다. 시작해 봅시다.

컴포넌트란 무엇인가요?

구성 요소를 사용하면 복잡한 애플리케이션을 작은 조각으로 나눌 수 있습니다. 예를 들어 일반적인 웹 애플리케이션에는 헤더, 사이드바, 콘텐츠, 바닥글과 같은 섹션이 있습니다.

Vue.js를 사용하면 각 부분을 구성 요소라고 하는 별도의 모듈 코드로 나눌 수 있습니다. 이러한 구성 요소를 확장한 다음 작업 중인 응용 프로그램에 연결할 수 있습니다. 구성 요소를 사용하는 것은 애플리케이션 작성 전반에 걸쳐 코드를 재사용할 수 있는 좋은 방법입니다.

블로그 애플리케이션이 있고 블로그 게시물 열을 표시하고 싶다고 가정해 보겠습니다. Vue 구성 요소를 사용하면 다음을 수행할 수 있습니다.

<blog-post></blog-post>
로그인 후 복사

Vue가 나머지를 처리합니다.

Vue 인스턴스를 DOM 요소에 마운트하는 간단한 HTML 페이지를 만듭니다. 이를 사용하여 구성 요소에 대해 알아봅니다. 다음은 샘플 HTML 페이지입니다.

<!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>
로그인 후 복사

위에서는 코드에 구성 요소가 없는 간단한 Vue 인스턴스를 만들었습니다. 이제 환영 메시지를 두 번 표시하려면 어떻게 해야 할까요?

Vue 인스턴스가 마운트된 위치에 p가 두 번 표시되도록 할 수도 있습니다. 이것은 작동하지 않습니다. ID에서 클래스로 변경해 보면 다음과 같은 결과가 표시됩니다.

<!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>
로그인 후 복사

여전히 작동하지 않습니다!

이 문제를 해결하는 유일한 방법은 구성 요소를 만드는 것입니다. 구성 요소를 어떻게 생성합니까?

구성 요소는 Vue.comComponent() 생성자를 사용하여 생성됩니다. 이 생성자는 구성 요소 이름(태그 이름이라고도 함)과 구성 요소 옵션이 포함된 개체라는 두 가지 매개 변수를 사용합니다. Vue.component()构造函数创建的。 这个构造函数有两个参数:你的组件的名字(也可以叫做标签名)和一个包含组件选项(options)的对象。

让我们使用上面的内容创建一个组件。

Vue.component(&#39;welcome-message&#39;, {
  data: function() {
  return {
   domain: &#39;Tutsplus&#39;
  }
  },
  template: &#39;<p>Welcome to {{ domain }}</p>&#39;
 })
로그인 후 복사

在上面,组件名称被称为welcome-message。 你的组件可以有你选择的任何名称。 然而重要的是,这个名字不会影响任何HTML标签,因为你不想重写它。

传递给构造函数的options对象包含数据和模板。 在创建组件时,你的数据应该是一个函数,如上所见。 被保存的数据应该作为一个对象返回。

在没有数据可以传递的情况下,传递如下的模板:

 Vue.component(&#39;welcome-message&#39;, {
  template: &#39;<p>Welcome to Tutsplus</p>&#39;
 })
로그인 후 복사

完成之后,可以通过使用传递给构造函数的名称将其当作常规HTML元素来在应用程序中使用组件。 它被这样调用:<welcome-message> </ welcome-message>

위 내용을 활용하여 컴포넌트를 만들어 보겠습니다.




VueJs Components


 
 

<welcome-message></welcome-message> <welcome-message></welcome-message> <welcome-message></welcome-message> <welcome-message></welcome-message>

<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>
로그인 후 복사

위에서 컴포넌트 이름은 welcome-message입니다. 구성 요소의 이름은 원하는 대로 지정할 수 있습니다. 그러나 중요한 것은 이 이름을 재정의하고 싶지 않기 때문에 이 이름이 HTML 태그에 영향을 미치지 않는다는 것입니다.

생성자에 전달된 옵션 개체에는 데이터와 템플릿이 포함되어 있습니다. 구성요소를 생성할 때 위에서 본 것처럼 데이터는 함수여야 합니다. 저장된 데이터는 객체로 반환되어야 합니다.

전송할 데이터가 없으면 다음과 같이 템플릿을 전달합니다.

<!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>
로그인 후 복사

완료되면 생성자에 전달된 이름을 사용하여 일반 HTML 요소로 처리하여 애플리케이션에서 해당 구성 요소를 사용할 수 있습니다. <welcome-message></welcome-message>와 같이 호출됩니다.

템플릿을 여러 번 출력하려면 아래와 같이 필요한 만큼 구성 요소를 호출하면 됩니다.

<!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>
로그인 후 복사

이렇게 하면 환영 메시지가 4번 표시됩니다.

구성 요소에 데이터 저장

위에서 데이터는 함수여야 하며, 여기에 포함된 정보는 객체로 반환되어야 한다고 언급했습니다. 왜 이런가요?

반환된 데이터가 객체가 아닌 경우 해당 데이터를 사용하는 구성 요소는 동일한 소스, 즉 공유 데이터를 공유합니다. 따라서 한 구성 요소의 데이터 변경은 다른 구성 요소에 영향을 미칩니다. 이는 데이터가 객체로 반환되는 경우와 동일하지 않습니다.

이것이 실제로 어떻게 작동하는지 확인하는 것이 중요합니다. 먼저, 데이터가 객체로 반환되는 경우를 살펴보자.

npm install -g vue-cli
로그인 후 복사

위에서 무슨 일이 일어났는지 추측할 수 있나요?

구성요소가 두 개 있는데, 데이터가 객체로 반환되지 않기 때문에 두 구성요소 모두 동일한 데이터 소스를 공유합니다. 내가 옳다는 것을 어떻게 증명하나요? 위 페이지를 브라우저에서 보면 한 구성 요소의 변경으로 인해 다른 구성 요소의 데이터도 변경되는 것을 볼 수 있습니다. 그러면 어떤 모습이어야 할까요?

예:

vue init webpack vue-component-app
로그인 후 복사

여기의 데이터는 객체로 반환되며 한 구성 요소의 변경 사항은 다른 구성 요소에 영향을 미치지 않습니다. 이 기능은 단일 구성 요소에 대해 수행됩니다. 애플리케이션을 구축할 때 이를 잊지 않는 것이 중요합니다.

컴포넌트 생성 및 사용

지금까지 배운 내용을 바탕으로 vue -cli를 사용하여 처음부터 새 Vue.js 프로젝트를 시작하여 구현해 보겠습니다. vue-cli가 컴퓨터에 설치되지 않은 경우 다음을 실행하여 새 Vue.js 프로젝트를 시작할 수 있습니다.

cd vue-component-app
npm install
npm run dev
로그인 후 복사

애플리케이션으로 이동하여 종속성을 설치하고 다음 명령 개발 서버를 실행합니다.

#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>
로그인 후 복사

먼저, Hello.vue로 애플리케이션을 초기화할 때 생성한 컴포넌트인 HelloWorld 컴포넌트의 이름을 바꾸겠습니다. 그런 다음 이 구성 요소를 응용 프로그램에서 사용할 전역 구성 요소로 등록합니다. 🎜🎜 따라서 Hello 구성 요소는 다음과 같아야 합니다. 🎜
#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 }
})
로그인 후 복사
로그인 후 복사
🎜환영 메시지를 보여주는 환영 텍스트와 데이터로 전달된 이름이 있습니다. 환영 메시지 아래의 버튼을 클릭하면changeName 메소드가 호출됩니다. 이름은 Henry에서 Mark로 변경됩니다. 🎜🎜이 구성 요소를 전역적으로 사용하려면 등록이 필요합니다. 이 일을 어디서 해야 할지 짐작할 수 있나요? 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 &#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 }
})
로그인 후 복사
로그인 후 복사

这里除了导入你的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>
로그인 후 복사

打开服务器,打开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>
로그인 후 복사

要在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>
로그인 후 복사

刷新页面以查看新页面。

范围组件样式

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>
로그인 후 복사

这与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允许你重用代码,你的页眉,页脚,登录面板和搜索栏可以用作组件。

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

相关文章:

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

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

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

위 내용은 Vue.js에서 구성요소와 해당 기능을 사용하는 방법을 자세히 설명해주세요.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!