이 글에서는 주로 Vue.js 컴포넌트에 대한 자세한 설명을 소개합니다. 컴포넌트는 Vue.js의 가장 강력한 기능 중 하나이므로 관심 있는 분들은 참고하시기 바랍니다
컴포넌트란 무엇입니까? 컴포넌트는 Vue.js의 가장 강력한 기능 중 하나입니다. 구성 요소는 HTML 요소를 확장하여 재사용 가능한 코드를 캡슐화할 수 있습니다. 높은 수준에서 구성 요소는 Vue.js의 컴파일러가 특수 기능을 추가하는 자체 정의 요소입니다. 어떤 경우에는 구성 요소가 is 속성으로 확장된 기본 HTML 요소의 형태일 수도 있습니다.
컴포넌트 등록은 어떻게 하나요?
end 메소드를 사용하여 컴포넌트를 생성한 후 Vue.comComponent 메소드를 사용하여 컴포넌트를 등록해야 합니다. Vue.extend 메소드의 형식은 다음과 같습니다:
var MyComponent = Vue.extend({ // 选项...后面再介绍 })이 생성된 구성 요소를 다른 곳에서 사용하려면 구성 요소 이름을 다음과 같이 지정해야 합니다.
HTML 태그에서 이 구성 요소 이름을 사용할 수 있습니다. 전체 구성 요소 등록 및 사용 예를 살펴보겠습니다.
<p id="example"> <my-component></my-component> </p>js 코드:
// 定义 var MyComponent = Vue.extend({ template: '<p>A custom component!</p>' }) // 注册 Vue.component('my-component', MyComponent) // 创建根实例 new Vue({ el: '#example' })출력 결과:
<p id="example"> <p>A custom component!</p> </p
중첩된 구성 요소
구성 요소 자체에도 구성 요소가 포함될 수 있습니다. 아래 상위 구성 요소에는 하위 구성 요소라는 구성 요소가 포함되어 있지만 이 구성 요소는 상위 구성 요소에서만 사용할 수 있습니다.
var child = Vue.extend({ template: '<p>A custom component!</p>' }); var parent = Vue.extend({ template: '<p>Parent Component: <child-component></child-component></p>', components: { 'child-component': child } }); Vue.component("parent-component", parent);위의 정의 프로세스는 더 번거롭고 매번 Vue.comComponent 및 Vue.extend 메서드를 호출할 필요가 없습니다.
// 在一个步骤中扩展与注册 Vue.component('my-component', { template: '<p>A custom component!</p>' }) // 局部注册也可以这么做 var Parent = Vue.extend({ components: { 'my-component': { template: '<p>A custom component!</p>' } } })
동적 구성 요소
<p id="dynamic"> <button id="home">Home</button> <button id="posts">Posts</button> <button id="archive">Archive</button> <br> <component :is="currentView"></component> </p>js 코드:
var vue = new Vue({ el:"#dynamic", data: { currentView: "home" }, components: { home:{ template: "Home" }, posts: { template: "Posts" }, archive: { template: "Archive" } } }); document.getElementById("home").onclick = function(){ vue.currentView = "home"; }; document.getElementById("posts").onclick = function(){ vue.currentView = "posts"; }; document.getElementById("archive").onclick = function(){ vue.currentView = "archive"; };구성 요소 및 v-구성 요소의 범위가 독립적이므로 구성 요소에 데이터를 전달할 수 없습니다. 데이터를 구성 요소에 전달하려면 props를 사용해야 합니다:
:item="item"
: index="$ index">
항목이 구성 요소에 자동으로 주입되지 않는 이유는 이로 인해 구성 요소가 현재 v와 긴밀하게 결합되기 때문입니다. -을 위한. 데이터의 출처를 명시적으로 선언하면
심층 대응 원칙
객체 를 vue 인스턴스에 데이터 옵션으로 전달하면 vue.js는 Object를 사용하여 해당 속성을 탐색합니다. DefineProperty는 이를 getter/setter로 변환합니다. 이는 ES5 기능이며 모든 vue.js는 IE8 이하를 지원하지 않습니다. 템플릿의
객체 속성 삭제를 감지할 수 없습니다. 데이터에 있어야 합니다. 이렇게 해야 vue.js가 응답하기 위해 getter/setter모드로 변환할 수 있습니다. 예:
var data = { a: 1 }; var vm = new Vue({ data: data }); // `vm.a` 和 `data.a` 现在是响应的 vm.b = 2 // `vm.b` 不是响应的 data.b = 2 // `data.b` 不是响应的그러나 인스턴스가 생성된 후 속성을 추가하고 관련성을 갖도록 하는 방법도 있습니다. set(
key,value) 인스턴스 메소드를 사용할 수 있습니다:
// `vm.b` 및 ` data.b`가 이제 반응합니다
对于普通对象可以使用全局方法:Vue.set(object, key, value):
Vue.set(data, 'c', 3)
// `vm.c` 和 `data.c` 现在是响应的
初始化数据:尽管Vue.js提供动态的添加相应属性,还是推荐在data对象上声明所有的相应属性。
不这么做:
var vm = new Vue({ template: '<p>{{msg}}</p>' }) // 然后添加 `msg` vm.$set('msg', 'Hello!')
应该这么做:
var vm = new Vue({ data: { // 以一个空值声明 `msg` msg: '' }, template: '<p>{{msg}}</p>' }) // 然后设置 `msg` vm.msg = 'Hello!'
组件完整案例
下面介绍的例子实现了模态窗口功能,代码也比较简单。
html代码:
<!-- 实现script定义一个模板 --> <script type="x/template" id="modal-template"> <!--模板是否显示通过v-show="show"来设置, transition设置动画效果--> <p class="modal-mask" v-show="show" transition="modal"> <p class="modal-wrapper"> <p class="modal-container"> <p class="modal-header"> <!--slot 相当于header占位符--> <slot name="header"> default header </slot> </p> <p class="modal-body"> <!--slot 相当于body占位符--> <slot name="body"> default body </slot> </p> <p class="modal-footer"> <!--slot 相当于footer占位符--> <slot name="footer"> default footer </slot> <button class="modal-default-button" @click="show = false">OK</button> </p> </p> </p> </p> </script> <p id="app"> <!--点击按钮时设置vue实例特性showModal的值为true--> <button id="show-modal" @click="showModal = true">show modal</button> <!--modal是自定义的一个插件,插件的特性show绑定vue实例的showModal特性--> <modal :show.sync="showModal"> <!--替换modal插件中slot那么为header的内容--> <h3 id="Custom-nbsp-Header">Custom Header</h3> </modal> </p>
js代码:
//定义一个插件,名称为modal Vue.component("modal", { //插件的模板绑定id为modal-template的DOM元素内容 template: "#modal-template", props: { //特性,类型为布尔 show:{ type: Boolean, required: true, twoWay: true } } }); //实例化vue,作用域在id为app元素下, new Vue({ el: "#app", data: { //特性,默认值为false showModal: false } });
css代码:
.modal-mask { position: fixed; z-index: 9998; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, .5); display: table; transition: opacity .3s ease; } .modal-wrapper { display: table-cell; vertical-align: middle; } .modal-container { width: 300px; margin: 0px auto; padding: 20px 30px; background-color: #fff; border-radius: 2px; box-shadow: 0 2px 8px rgba(0, 0, 0, .33); transition: all .3s ease; font-family: Helvetica, Arial, sans-serif; } .modal-header h3 { margin-top: 0; color: #42b983; } .modal-body { margin: 20px 0; } .modal-default-button { float: right; } /* * the following styles are auto-applied to elements with * v-transition="modal" when their visiblity is toggled * by Vue.js. * * You can easily play with the modal transition by editing * these styles. */ .modal-enter, .modal-leave { opacity: 0; } .modal-enter .modal-container, .modal-leave .modal-container { -webkit-transform: scale(1.1); transform: scale(1.1); }
相关文章:
위 내용은 강력한 Vue.js 구성 요소에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

VueUse 是 Anthony Fu 的一个开源项目,它为 Vue 开发人员提供了大量适用于 Vue 2 和 Vue 3 的基本 Composition API 实用程序函数。本篇文章就来给大家分享几个我常用的几个 VueUse 最佳组合,希望对大家有所帮助!

Vue3如何更好地使用qrcodejs生成二维码并添加文字描述?下面本篇文章给大家介绍一下Vue3+qrcodejs生成二维码并添加文字描述,希望对大家有所帮助。

如何使用VueRouter4.x?下面本篇文章就来给大家分享快速上手教程,介绍一下10分钟快速上手VueRouter4.x的方法,希望对大家有所帮助!

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

本篇文章给大家整理分享8个GitHub上很棒的的 Vue 项目,都是非常棒的项目,希望当中有您想要收藏的那一个。

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

드림위버 CS6
시각적 웹 개발 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

뜨거운 주제



