Vue.js 什么是组件以及如何定义组件?

示例

Vue中的组件就像小部件。它们使我们能够编写具有期望行为的可重用自定义元素。

它们不过是对象,可以包含根或任何Vue实例可以包含的任何/所有选项,包括要呈现的HTML模板。

组件包括:

  • HTML标记:组件的模板

  • CSS样式:如何显示HTML标记

  • JavaScript代码:数据和行为

它们可以分别写在单独的文件中,也可以写成带有.vue扩展名的单个文件。以下是显示两种方式的示例:

.VUE-作为组件的单个文件

<style>  
    .hello-world-compoment{  
        color:#eeeeee;  
        background-color:#555555; 
    }  
</style>  

<template>
    <div class="hello-world-component">
        <p>{{message}}</p>
        <input @keyup.enter="changeName($event)"/>
    </div>
</template>

<script>
    export default{            
        props:[ /* to pass any data from the parent here... */ ],   
        events:{ /* event listeners go here */},
        ready(){
            this.name= "John";
        },
        data(){
           return{
              name:''
           }
        },
        computed:{
            message(){
                return "来自...的问候 " + this.name;
            }
        },
        methods:{
            // this could be easily achieved by using v-model on the <input> field, but just to show a method doing it this way.
            changeName(e){
               this.name= e.target.value;
            }
        }  
    }
</script>

分开的文件

hello-world.js-组件对象的JS文件

export default{
    template:require('./hello-world.template.html'),
    props:[ /* to pass any data from the parent here... */ ],  
    events:{ /* event listeners go here */ },
    ready(){
        this.name="John";
    },
    data(){
        return{
            name:''
        }
    },
    computed:{
        message(){
            return "Hello World! from " + this.name;
        }
    },
    methods:{
        changeName(e){
            let name = e.target.value;
           this.name= name;
        }
    }
}

hello-world.template.html

<div class="hello-world-component">
    <p>{{message}}</p>
    <input class="form-control input-sm" @keyup.enter="changeName($event)">
</div>

hello-world.css

 .hello-world-compoment{  
    color:#eeeeee;  
    background-color:#555555; 
}

这些示例使用es2015语法,因此对于较旧的浏览器,需要Babel将其编译为es5。
需要Babel以及Browserify + vueifyWebpack + vue-loader进行编译hello-world.vue。

现在我们已经hello-world定义了组件,我们应该在Vue中注册它。

这可以通过两种方式完成:

注册为全局组件
在main.js文件中(指向应用程序的入口),我们可以使用Vue.component以下命令全局注册任何组件:

import Vue from 'vue'; // 请注意,在这种情况下,“ vue”是使用“ npm install Vue”安装的节点模块。
Vue.component('hello-world', require('./hello-world');  // 全球注册

new Vue({
    el:'body',

    // 模板可以定义为内联字符串,如下所示:
    template:'<div class="app-container"><hello-world></hello-world></div>'
});

或在父组件或根组件中本地注册

import Vue from 'vue'; // 请注意,在这种情况下,“ vue”是使用“ npm install Vue”安装的节点模块。
import HelloWorld from './hello-world.js';  

new Vue({
    el:'body',
    template:'<div class="app-container"><hello-world></hello-world></div>",

    components:{HelloWorld}  // 本地注册
});

全局组件可以在Vue应用程序中的任何位置使用。

本地组件仅可在注册它们的父组件中使用。

片段组件
您可能会收到一个控制台错误,告诉您您无法做某事,因为您的片段组件。要解决此类问题,只需将组件模板包装在一个标签(例如)内<div>。