>  기사  >  웹 프론트엔드  >  Vue 컴포넌트를 작성하는 방법은 무엇입니까?

Vue 컴포넌트를 작성하는 방법은 무엇입니까?

亚连
亚连원래의
2018-06-23 15:43:00970검색

이 기사에서는 Vue 구성 요소 3가지의 작성 형식을 주로 소개하며, 관심 있는 친구들은 참고할 수 있습니다.

이 기사의 예는 참고용으로 Vue 구성 요소의 작성 형식을 공유합니다. 다음과 같습니다

첫 번째는 스크립트 태그를 사용합니다

<!DOCTYPE html>
<html>
  <body>
    <p id="app">
      <my-component></my-component>
    </p>

    <-- 注意:使用<script>标签时,type指定为text/x-template,意在告诉浏览器这不是一段js脚本,浏览器在解析HTML文档时会忽略<script>标签内定义的内容。-->

    <script type="text/x-template" id="myComponent">//注意 type 和id。
      <p>This is a component!</p>
    </script>
  </body>
  <script src="js/vue.js"></script>
  <script>
    //全局注册组件
    Vue.component(&#39;my-component&#39;,{
      template: &#39;#myComponent&#39;
    })

    new Vue({
      el: &#39;#app&#39;
    })

  </script>
</html>

두 번째는 템플릿 태그를 사용합니다

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
    <p id="app">
      <my-component></my-component>
    </p>

    <template id="myComponent">
      <p>This is a component!</p>
    </template>
  </body>
  <script src="js/vue.js"></script>
  <script>

    Vue.component(&#39;my-component&#39;,{
      template: &#39;#myComponent&#39;
    })

    new Vue({
      el: &#39;#app&#39;
    })

  </script>
</html>

세 번째단일 파일 구성 요소

이 방법은 vue 단일 페이지 애플리케이션에서 일반적으로 사용됩니다. 자세한 내용은 공식 웹사이트를 참조하세요: https://cn.vuejs.org/v2/guide/single-file-comComponents.html

.vue 접미사, Hello.vue 구성 요소가 포함된 파일을 생성하고 해당 위치에 배치합니다. the Components 폴더

<template>
 <p class="hello">
  <h1>{{ msg }}</h1>
 </p>
</template>

<script>
export default {
 name: &#39;hello&#39;,
 data () {
  return {
   msg: &#39;欢迎!&#39;
  }
 }
}
</script>

app.vue

<!-- 展示模板 -->
<template>
 <p id="app">
  <img src="./assets/logo.png">
  <hello></hello>
 </p>
</template>

<script>
// 导入组件
import Hello from &#39;./components/Hello&#39;

export default {
 name: &#39;app&#39;,
 components: {
  Hello
 }
}
</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>

위 내용은 앞으로 모두에게 도움이 되기를 바랍니다.

관련 글:

JavaScript에서 모두 선택 취소 효과 구현하는 방법

JavaScript를 사용하여 왼쪽 메뉴 효과 구현하는 방법

vue를 사용하여 토큰 확인 구현하는 방법

방법 Javascript 메커니즘을 사용하여 맞춤 이벤트 구현

위 내용은 Vue 컴포넌트를 작성하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.