简介
之前文件的组织是以.HTML、.js以及.css/less/scss这些文件举行垂直支解的,而Vue中我们以组件为单元组织,因而,最好的体式格局是把这些差别的范例的文件与组件相干的部份,缭绕组件组合成一个文件即.vue文件,我称其为程度支解。别的,在<template>
中写模板也比本来的字符串情势的模板轻易的多。
在webpack内里要加载*.vue文件,须要下面两个包
$npm install vue-loader vue-template-compiler
webpack增加Loader设置
{
test: /\.vue$/,
use: [
'vue-loader'
]
}
......
resolve: {
extensions: ['.js', '.vue'],
alias: {
'Vue': 'vue/dist/vue.js'
}
}
webpack的resolve
选项,用来设置剖析import
、require
中的途径的细节,extensions
就是在某文件没写扩展名时,默许的寻觅扩展名。如import App from './App'
中,没有App.js
就找App.vue
。alias
是给途径起个别号,轻易一点,如import Vue from 'Vue'
即示意import Vue from 'vue/dist/vue.js'
然后就能够编写代码了
<!--App.vue-->
<template>
<div id="app">
<h1 class="text-color">{{heading}}</h1>
</div>
</template>
<script>
export default {
data(){
return {heading:'My Todo App!'}
}
}
</script>
<style>
.text-color {
color:#009A61
}
</style>
//index.js
import Vue from 'Vue'
import App from './App'
new Vue({
el: '#app-1',
template: '<App/>',
components: { App },
//render: h => h(App)
})
<!--index.html-->
<body>
<div id="app-1"></div>
</body>
文件App.vue
即所谓的单文件组件,我们看到了模板、款式和JS是怎样程度支解的。
另有要注意的是,页面原始的<div id="app-1"></div>
将会被组件替换掉。
模板写在以下内容中:
<template>
</template>
JS写在以下内容中:
<script>
export default {
//options
}
</script>
css写在以下内容中:
<style>
</style>
我们在index.js中援用这个App.vue文件组件,这里让它作为实例#app-1
的子组件引入,也能够运用衬着函数运用它。
一个例子
这里是官网上一个单文件多层组件的示例。App2.vue
在子组件BaseInputText.vue中,有以下代码
<template>
<input type="text" class="input" :value="value" v-on="eventDict">
</template>
<script>
export default {
props: {
value: {
type: String,
default: ""
}
},
computed: {
eventDict() {
var self = this;
//假如基层组件另有自定义事宜触发,那末都保存在$listeners中,这里没有基层组件
return Object.assign({}, this.$listeners, {
input: function(event) {
self.$emit("input", event.target.value);
}
});
}
}
};
</script>
这里在无参的v-on
中绑定了一个事宜对象,该对象中除了有必需的input
事宜,并与this.$listeners
兼并,this.$listeners
包含了该子组件的一切基层组件(假如有的话)中的自定义事宜。
就像示例中所做的那样,属性和要领都集合在上层的组件中,这里是TodoList.vue组件,经由过程Props下发数据到子组件。